我为此工作,但没有找到解决问题的办法。
这是我的代码。此代码在pthread_create和pthread_join行上给出错误。我尽一切努力解决了这个问题,但是我做不到。

  #include <stdio.h>
  #include <pthread.h>
  #define array_size 1000
  #define no_threads 10

 float a[array_size];
 int global_index = 0;
 int sum = 0;
 pthread_t mutex_t ,mutex1;

 void *slave(void *ignored)
{
 int local_index, partial_sum = 0;
 do {
    pthread_t mutex_t ,lock(mutex1);
      local_index = global_index;
      global_index++;
    pthread_t mutex ,unlock(mutex1);

    if (local_index < array_size)
        partial_sum += *(a + local_index);
}
while
 (local_index < array_size);

pthread_t mutex , lock(mutex1);
sum += partial_sum;
pthread_t mutex_t , unlock(mutex1);

 return 0;
}

 main()
 {
  int i;
  pthread_t thread_x[10];
  pthread_mutex_init(&mutex1, NULL);

  for (i = 0; i < array_size; i++)
   a[i] = i+1;

  for (i = 0; i < no_threads ; i++)
  pthread_create(&thread_x[i] , NULL, slave,NULL);

  for (i = 0; i < no_threads; i++)
    pthread_join(&thread_x[i] , NULL);


  printf("The sum of 1 to %d is %d\n", array_size, sum);
}

最佳答案

我已经更新了您的代码(pt1.c),我想您正在寻找类似的东西。

#include <stdio.h>
#include <pthread.h>
#define array_size 1000
#define no_threads 10

float a[array_size];
int global_index = 0;
int sum = 0;
pthread_mutex_t mutex1;

void *slave(void *ignored)
{
    int local_index, partial_sum = 0;
    do {
        pthread_mutex_lock(&mutex1);
        local_index = global_index;
        global_index++;
        pthread_mutex_unlock(&mutex1);

        if (local_index < array_size)
            partial_sum += *(a + local_index);
    }
    while(local_index < array_size);

    pthread_mutex_lock(&mutex1);
    sum += partial_sum;
    pthread_mutex_unlock(&mutex1);

    return 0;
}

main()
{
    int i;
    pthread_t thread_x[10];
    pthread_mutex_init(&mutex1, NULL);

    for (i = 0; i < array_size; i++)
        a[i] = i+1;

    for (i = 0; i < no_threads ; i++)
        pthread_create(&thread_x[i] , NULL, slave,NULL);

    for (i = 0; i < no_threads; i++)
        pthread_join(thread_x[i] , NULL);

    printf("The sum of 1 to %d is %d\n", array_size, sum);
}


您应该将此代码编译为
gcc -pthread pt1.c

输出:

1至1000的总和为500500

关于c - 如何在C中将具有线程的数组元素求和?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33949085/

10-11 19:41