在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 created40
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
最满意答案
问题是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.
相关问答
更多-
用Cython编程 - 具有共享代码的ndarray的常规类型(Programming with Cython - General types for ndarray with shared code)[2023-03-26]
这里的主要困难是你使用两种类型: 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 ...
-
迭代一个ndarray(Iterating over an ndarray)[2022-06-18]
在你的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 ... -
cython:ndarray字符串的内存视图(或直接ndarray索引)(cython: memory view of ndarray of strings (or direct ndarray indexing))[2021-09-10]
问题是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)
-
从numpy.ndarray初始化cython中的memoryview切片(Initialize slices of memoryview in cython from numpy.ndarray)[2023-02-20]
我可以找到两个选项: 如果您键入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 ... -
需要使用`non-ndarray sequence`进行numpy基本索引的示例(Need examples for numpy basic indexing with `non-ndarray sequence`)[2022-04-01]
这是一个有趣的便利。 让我们说我有以下数组: 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))] 但这仍然没有用,所以我假设有负值或零值 ...