如何将数组的元素与C中的线程相加?

时间:2015-11-27 01:17:25

标签: c pthreads

我在这方面工作,但我找不到问题的解决方案。 这是我的代码。此代码在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);
}

1 个答案:

答案 0 :(得分:3)

我已经更新了你的代码(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