c同步中的多线程

Multi threading in c synchronization

我正在尝试读取数组限制和数字,并尝试使用第一个线程找出一半数字的总和,并使用线程 2 找出数组另一半的总和,但线程 2 在读取后立即 运行限制如果数组使用线程 1

#include <stdio.h>
#include <pthread.h>

 void *method(void *);
 int a[10];

 int main(){
   int error;
   pthread_t id1,id2;
   pthread_attr_t attr1,attr2;
   pthread_attr_init(&attr1);
   pthread_attr_init(&attr2);
   error = pthread_create(&id1,&attr1,method,(int *)0);
   error = pthread_create(&id2,&attr2,method,(int *)1);
   //wait();
   error = pthread_join(id1,NULL);
   if(error!=0){
     printf("\n Error in Joining 1");
   }
   wait();
   error = pthread_join(id2,NULL);
   if(error!=0){
     printf("\n Error in Joining 2");
   }
   return 0;
 }

 void *method(void *args){
   int ch = (int *)args;
   int i,n,sum=0;
   if(ch==0) {
     printf("\nEnter the limit : ");
     scanf("%d",&n);
     printf("\nEnter the Numbers : ");
     for (i = 0; i < n; i++) {
       scanf("%d",&a[i]);
     }
     for (i = 0; i < n/2; i++) {
       sum+=a[i];
     }
     printf("\nThe sum of first n/2 elements : %d",sum);
   } else {
     sum = 0;
     for (i = (n/2)+1; i < n; i++) {
       sum+=a[i];
     }
     printf("\nThe sum of first n elements : %d",sum);   
   }    
 }

来自compiling/running的输出:

[leox@leox ~/nos_lab $ gcc multi.c -lpthread
multi.c: In function ‘method’:
multi.c:27:12: warning: initialization makes integer from pointer without a cast [enabled by default]
   int ch = (int *)args;
        ^
leox@leox ~/nos_lab $ ./a.out
The sum of first n elements : 0
Enter the limit : 

ScreenShot

如果您不希望线程 2 在线程 1 完成之前启动,最简单的解决方法是将线程 2 的 pthread_create 移动到线程 1 的 pthread_join 之后。

但是,你还是有问题,因为nsummethod的局部变量,两个线程会分别调用method。您可以像使用 a 那样将这些变量移出为全局变量,或者您可以设置一个结构作为指向 method 线程函数的指针传递,该线程函数包含您想要 use/update.

另请注意,让一个线程等待另一个线程完全完成会消除您可能从线程中获得的任何性能改进。