在C中同步线程

在C中同步线程,c,multithreading,synchronization,pthreads,C,Multithreading,Synchronization,Pthreads,我正在编写一个程序来计算向量的偶数。我输入了一些线程,这些线程必须被创建来并行分析向量 结果始终必须为500,但有时会发生变化(485、512、586、410)。我想问题在于线程的同步,但我正在使用连接,所以我不知道为什么这个问题持续存在 解决 我的代码: #include<stdio.h> #include<stdlib.h> #include<sys/shm.h> #include <pthread.h> #define VECTOR_LEN

我正在编写一个程序来计算向量的偶数。我输入了一些线程,这些线程必须被创建来并行分析向量

结果始终必须为500,但有时会发生变化(485、512、586、410)。我想问题在于线程的同步,但我正在使用连接,所以我不知道为什么这个问题持续存在

解决

我的代码:

#include<stdio.h>
#include<stdlib.h>
#include<sys/shm.h>
#include <pthread.h>

#define VECTOR_LENGTH 1000

int vector[VECTOR_LENGTH];
int sum = 0;
int quantity_positions;

void VerifyVector(int i){
    int j = 0;
    int vector_sum = 0;

        for (j = (i * quantity_positions); j < ((i + 1) * quantity_positions); j++)
      if ((vector[j] % 2) == 0)
        vector_sum++;
    //printf("Thread num %d sum value: %d\n", i, vector_sum);
        pthread_exit(vector_sum);
}

int main(int argc, char*argv[]){
  int i, j;
  int threads = 0;
  int rest = 0;

  for (i = 0; i < VECTOR_LENGTH; i++)
    vector[i] = i;

  threads = atoi(argv[1]);

  if (threads <= 0)
    threads = 1;

  int threads_result[threads];

  pthread_t threads_id[threads];

  quantity_positions = VECTOR_LENGTH / threads;

  if ((quantity_positions * threads) != VECTOR_LENGTH)
    rest = VECTOR_LENGTH - (quantity_positions * threads);

  if (threads == 1)
    for (i = 0; i < quantity_positions; i++){
      if ((vector[i] % 2) == 0)
        sum++;
    }
  else {
    for (i = 1; i < threads; i++){
      pthread_create(&threads_id[i], NULL, VerifyVector, i);

    }

    for(i = 1; i < threads; i++)
      pthread_join(threads_id[i], &threads_result[i]);

    for (i = 1; i < threads; i++)
      sum += threads_result[i];

    for (j = (0 * quantity_positions); j < (quantity_positions + rest); j++)
      if ((vector[j] % 2) == 0)
    sum++;

  }

  printf("The total is: %d\n", sum);

  return 0;
}
#包括
#包括
#包括
#包括
#定义向量长度1000
int向量[向量长度];
整数和=0;
int数量和位置;
无效验证向量(int i){
int j=0;
int向量_和=0;
对于(j=(i*数量位置);j<((i+1)*数量位置);j++)
如果((向量[j]%2)==0)
向量_和++;
//printf(“线程数%d和值:%d\n”,i,向量\u和);
pthread_exit(vector_sum);
}
int main(int argc,char*argv[]){
int i,j;
int线程=0;
int-rest=0;
对于(i=0;i
此外,您不需要synchro,因为您在线程运行期间没有对向量进行变异

您需要的是修复molbdnilo/my comments中列出的所有错误。停止使用令人困惑的i、j、k单字母变量,除非您确实需要,否则不要使用全局变量。修复数组索引


我不理解所有“父进程”的东西:(

Wots与'shmget'?同一进程中的线程不需要显式调用来共享内存。我看不到任何同步。
join
不会在线程之间同步,它只会导致当前线程等待特定的其他线程完成。请阅读有关互斥锁的内容。我还担心您似乎认为数组索引从1开始。变量“j”是全局变量,由对VerifyVector的所有调用共享:(本地和全球VAR都命名为“i”,如果不是一个bug的话,就是混乱和糟糕的做法。这不是答案。这没有提供问题的答案。要评论或要求作者澄清,请在他们的帖子下方留下评论。@Achrome等。你认为共享的全局“j”不是问题的原因吗?