首页 \ 问答 \ 在2个线程之间交替(Alternate between 2 threads)

在2个线程之间交替(Alternate between 2 threads)

我想制作一个程序,用2个函数写入1到100之间的奇数和偶数,第一个函数打印前5个奇数,第二个函数打印前5个偶数,然后再返回第一个函数进行打印第二个5个奇数等等。 在这个程序中,我想在2线程之间交替,但我找不到解决方案。 这是我的代码,在这段代码中我创建了40线程。有谁知道如何在2个线程之间进行交替并找到相同的输出。

#include<stdio.h>
#include<pthread.h>
pthread_t tid[40];
int pair=2;
int impair=1 ;
pthread_mutex_t lock;

void* genpair(void *arg)
{
    pthread_mutex_lock(&lock);
    int i = 0;
    for (i=0 ; i<5 ; i++,pair+=2)
    {
        printf("%d ",pair) ;
    }
printf("  ");    
pthread_mutex_unlock(&lock);

    return NULL;
}
void* genimpair(void *arg)
{
    pthread_mutex_lock(&lock);
    int i = 0;
    for (i=0 ; i<5 ; i++,impair+=2)
    {
         printf("%d ",impair) ;
    }
printf("  ");    
pthread_mutex_unlock(&lock);

    return NULL;
}

int main(void)
{
    int i = 0;
    int j=0 ;
    int err;

    if (pthread_mutex_init(&lock, NULL) != 0)
    {
        printf("\n mutex init failed\n");
        return 1;
    }

    for(j=0 ; j<20 ; j+=2)  
    {
        pthread_create(&(tid[j]), NULL, &genpair, NULL);
        pthread_create(&(tid[j+1]), NULL, &genimpair, NULL);
        pthread_join(tid[j], NULL);
        pthread_join(tid[j+1], NULL);           
    }

    pthread_mutex_destroy(&lock);

    return 0;
}

I wanted to make a program that writes the odd and even numbers between 1 and 100 with 2 functions , the first function prints the first 5 odd numbers , the second function prints the first 5 even numbers and again we return to the first function to print the second 5 odd numbers and so on . In this program i wanted to alternate between only 2 threads , but i can't find the solution . Here's my code , in this code i created 40 threads.Does anyone knows how to alternate between 2 threads and find the same output.

#include<stdio.h>
#include<pthread.h>
pthread_t tid[40];
int pair=2;
int impair=1 ;
pthread_mutex_t lock;

void* genpair(void *arg)
{
    pthread_mutex_lock(&lock);
    int i = 0;
    for (i=0 ; i<5 ; i++,pair+=2)
    {
        printf("%d ",pair) ;
    }
printf("  ");    
pthread_mutex_unlock(&lock);

    return NULL;
}
void* genimpair(void *arg)
{
    pthread_mutex_lock(&lock);
    int i = 0;
    for (i=0 ; i<5 ; i++,impair+=2)
    {
         printf("%d ",impair) ;
    }
printf("  ");    
pthread_mutex_unlock(&lock);

    return NULL;
}

int main(void)
{
    int i = 0;
    int j=0 ;
    int err;

    if (pthread_mutex_init(&lock, NULL) != 0)
    {
        printf("\n mutex init failed\n");
        return 1;
    }

    for(j=0 ; j<20 ; j+=2)  
    {
        pthread_create(&(tid[j]), NULL, &genpair, NULL);
        pthread_create(&(tid[j+1]), NULL, &genimpair, NULL);
        pthread_join(tid[j], NULL);
        pthread_join(tid[j+1], NULL);           
    }

    pthread_mutex_destroy(&lock);

    return 0;
}

原文:https://stackoverflow.com/questions/33423221
更新时间:2023-03-28 21:03

最满意答案

问题是numpy数组dtypes必须有一个固定的大小。 当你创建一个“字符串”数组时,你实际上是在制作一个固定长度字符数组的数组。 尝试这个:

import numpy as np

array = np.array(["cat", "in", "a", "hat"])
array[2] = "Seuss"
print(array)
# ['cat' 'in' 'Seu' 'hat']
print(array.dtype)
# dtype('|S3')
print(array.dtype.itemsize)
# 3

考虑到这一点,你可以这样:

cdef void abc(char[:, ::1] in_buffer):
    cdef char * element
    element = address(in_buffer[1, 0])

然后当你将数组传递给abc你需要做类似的事情:

a = np.array(['ABC', 'D', 'EFGHI'])
array_view = a.view('uint8').reshape(a.size, a.dtype.itemsize)
abc(array_view)

这只是一种方法,但这是我推荐的方法,却不知道你想要做什么。


The issue is that numpy array dtypes have to have a fixed size. When you make an array of "strings" you're actually making an array of fixed length char arrays. Try this:

import numpy as np

array = np.array(["cat", "in", "a", "hat"])
array[2] = "Seuss"
print(array)
# ['cat' 'in' 'Seu' 'hat']
print(array.dtype)
# dtype('|S3')
print(array.dtype.itemsize)
# 3

With that in mind, you could something like this:

cdef void abc(char[:, ::1] in_buffer):
    cdef char * element
    element = address(in_buffer[1, 0])

Then when you pass your arrays to abc you'll need to do something like:

a = np.array(['ABC', 'D', 'EFGHI'])
array_view = a.view('uint8').reshape(a.size, a.dtype.itemsize)
abc(array_view)

This is only one approach, but it's the one I would recommend without knowing more about what you're trying to do.

相关问答

更多
  • 这里的主要困难是你使用两种类型: numpy dtype ,它是一个运行时确定的Python对象,和 由Cython融合类型指定的类型,这是编译时确定的C类型。 在这两种类型之间进行转换并不是特别容易(因为这可能会在运行时使用信息生成编译时需要的东西),但是它并不能很容易地转换“dtype-> fused type”有道理,你不能转换其他方式。 为了解决这个问题,我使用了虚拟参数 - 这些参数没有被使用,但强制Cython生成特定类型的代码。 第二个问题是,你希望你的a和b数组是不同的类型(我最初误解你的评 ...
  • 首先使用read_csv ,然后使用read_csv转换为numpy array : import pandas as pd df = pd.read_csv('file', header=None) print(df) 0 1 2 3 4 0 12 employed 32 happy 1 1 21 unemployed 31 poor 0 2 34 rich 45 unhapppy 0 arr ...
  • 在你的nditer循环中,你不会迭代数组的元素。 您正在迭代0维子阵列,每个子阵列都是单个单元格单元的只读视图。 您看到的类型是0维子阵列的类型,而不是实际的数组内容。 如果要迭代对象axes.flat的N维数组中的object ,最简单的方法是遍历axes.flat : for ax in axes.flat: do_whatever_with(ax) 对于其他dtypes的数组,通常最好避免显式迭代。 In your nditer loop, you're not iterating over ...
  • 问题是numpy数组dtypes必须有一个固定的大小。 当你创建一个“字符串”数组时,你实际上是在制作一个固定长度字符数组的数组。 尝试这个: import numpy as np array = np.array(["cat", "in", "a", "hat"]) array[2] = "Seuss" print(array) # ['cat' 'in' 'Seu' 'hat'] print(array.dtype) # dtype('|S3') print(array.dtype.itemsize) ...
  • 花哨的索引是这样做的numpythonic方式: mapped = meanings[flags] 或通常更快的等价物: mapped = np.take(meanings, flags) Fancy indexing is the numpythonic way of doing it: mapped = meanings[flags] or the often faster equivalent: mapped = np.take(meanings, flags)
  • 我可以找到两个选项: 如果您键入B1和B2作为内存视图,它可以工作。 您可以访问memoryview的base属性来获取cvarray和index: A.base[0,:,:] = B1 A.base[1,:,:] = B2 我认为这不一定适用于所有与memoryview兼容的对象(它们需要定义缓冲区接口而不是有用的__getitem__ ),但它应该适用于大多数,包括cvarray 。 I can find two options: It works if you type B1 and B2 as a ...
  • 这是一个有趣的便利。 让我们说我有以下数组: arr = np.arange(100) 如果我很傻,我可以像这样切片: arr[:30, ..., np.newaxis] ( Ellipsis在这里没有任何帮助,但我可以把它放在那里)。 基本上,这告诉基本切片采取前30个元素,然后添加一个新轴。 如果我宁愿(或者无论出于何种原因它更方便),我可以像这样完成相同的切片: arr[[slice(0, 30), Ellpisis, np.newaxis]] 如果我有一个2d数组: arr = arr.res ...
  • 如果我理解正确,您只想将第二列设置为零(如果它的值大于1000)? 我将您的示例扩展为至少有两行,但只是测试它也可以使用一行: b = np.array([[123, 456], [789, 101112]]) mask = b[:,1] > 1000 b[mask,1] = 0 print b 我定义了mask以更好地解释它 - 你可以用它替换它。然后mask是一个布尔向量,每行有一个元素,在本例中为[False, True] 。 在最后一步中,该mask用于掩盖所选行并将 ...
  • 通常, x.data显示的x.data并不适合您使用。 x.data是缓冲区,可以在其他需要缓冲区的上下文中使用。 np.frombuffer(x.data,dtype=float) 复制你的x 。 np.frombuffer(x[3:].data,dtype=float) 这复制了x[3:] 。 但是从Python中你不能使用x.data ,向它添加192位(3 * 8 * 8),并期望获得x[3:] 。 我经常使用__array_interface__['data']值来检查两个变量是否共享一个数据 ...
  • 所以,假设有一个NAN值,我更改了代码以包含这个: # converting the list into a numpy like array values = np.asarray(valueList) # values = {ndarray}[ 273. 275. 255. ..., 192. 180. 176.] # removing NANs values = values[np.logical_not(np.isnan(values))] 但这仍然没有用,所以我假设有负值或零值 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。