我正在尝试实现一种多线程方法来求和数组中的元素。我的问题很基本,我想对2个数组的元素求和,并将结果放在第三个数组中,即sumArray [x] = array1 [x] + array2 [x]。我必须使用pthreads,不能使用OpenMP或任何类似的隐式多线程库。我想出了一个实现,但是它不求和数组元素(我已经通过打印出不包含两个数组之和的结果数组进行了测试)。如果有人可以帮助我指出实施中出了什么问题,我将不胜感激!注意,Im还应该将线程数作为命令行参数。
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define SIZE 362880
#define NUM_THREADS 5
typedef struct coord {
int nbThreads;
int array1[SIZE];
int array2[SIZE];
int array3[SIZE];
} Item;
void * sumArrays(void *index) {
int i, s, itemsToHandle, start, stop;
itemsToHandle = SIZE / ((Item *) index)->nbThreads;
s = * (int *) index;
start = s * itemsToHandle;
if(s != (((Item *) index)->nbThreads - 1)) start = start + itemsToHandle;
else stop = ((Item *) index)->nbThreads;
for(i = start + 1; i < stop; i++) {
((Item *) index)->array3[i] = ((Item *) index)->array1[i] + ((Item *) index)->array2[i];
}
return(NULL);
}
int main(int argc, char* argv[]) {
int threads = atoi(argv[1]);
Item * arrays = (Item *)malloc(sizeof(Item));
arrays->nbThreads = threads;
for(int i = 0; i < SIZE; i++) {
arrays->array1[i] = 1;
arrays->array2[i] = 1;
}
pthread_t ids[threads];
int i;
for(i = 0; i < threads; i++) {
pthread_create(&ids[i], NULL,sumArrays,&arrays);
void *status;
pthread_join(ids[i], &status);
}
// I also tried to do another for loop for pthread join
for(int i = 0; i < 10; i++) {
printf("Array1 = %d\n", arrays->array1[i]);
printf("Array2 = %d\n", arrays->array2[i]);
printf("Array3 = %d\n", arrays->array3[i]);
}
}
您能否检查一下下面的void * sumArrays(void *index)
功能行?
s = * (int *) index;
该值对于所有线程都是相同的。
创建线程时
pthread_create(&ids[i], NULL,sumArrays,&arrays);
无需应用&运算符:arrays
已经是一个指针。
pthread_create(&ids[i], NULL,sumArrays, arrays);
由于价值start
和stop
为您的所有线程的算法将无法工作按预期相同。如果我理解正确,则希望在线程之间共享一些工作(添加)。第一个线程必须从index开始添加0
。似乎不是这样:for(i = start + 1; i < stop; i++) {
我希望以上评论对您有所帮助。
还要检查此链接:使用pthreads处理数组/向量的各个部分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句