【问题标题】:Multithreading (pthreads) to sum array elements in C多线程(pthreads)对C中的数组元素求和
【发布时间】:2016-11-06 12:06:39
【问题描述】:

我正在尝试实现一种多线程方法来对数组中的元素求和。我的问题很基本,我想对 2 个数组的元素求和,并将结果放入第三个数组,即 sumArray[x] = array1[x] + array2[x]。我必须使用 pthread,我不能使用 OpenMP 或任何类似的隐式多线程库。我想出了一个实现,但它没有对数组元素求和(我通过打印出结果数组来测试它,它不包含两个数组的总和)。 如果有人可以帮助我指出我在实施中出错的地方,我将不胜感激! 注意,我也应该将线程数作为命令行参数。

#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]);
    }
}

【问题讨论】:

    标签: c arrays multithreading pthreads


    【解决方案1】:

    你能检查void * sumArrays(void *index)函数下面的那行吗?

    s = * (int *) index;
    

    所有线程的值都相同。

    线程创建时

    pthread_create(&ids[i], NULL,sumArrays,&arrays);
    

    不需要应用&运算符:arrays已经是一个指针了。

    pthread_create(&ids[i], NULL,sumArrays, arrays);
    

    由于startstop 的值对于所有线程都相同,因此您的算法将无法按预期工作。如果我理解正确,您希望在线程之间共享一项工作(添加)。第一个线程必须从索引0 开始添加。情况似乎并非如此: for(i = start + 1; i &lt; stop; i++) { 希望以上 cmets 对您有所帮助。

    另请查看此链接:Using pthreads to process sections of an array/vector

    【讨论】:

    • 那么在s = * (int *) index语句中,我愿意得到线程ID,不就是这样吗?如果我愿意将工作分散到所有线程中,我将如何设置开始和结束?
    • 不!那不会给你线程ID。我认为您不需要,但在 Linux 系统上,您可以使用 getid() 获取线程 ID:#include &lt;sys/types.h&gt; pid_t tid = gettid();
    • 您可能会发现此链接很有用:stackoverflow.com/questions/22694042/…
    猜你喜欢
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    相关资源
    最近更新 更多