c - c同步中的多线程

标签 c multithreading pthreads

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

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

编译/运行的输出:

[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 移动到 pthread_join 之后线程 1.

但是,您仍然有问题,因为nsummethod 的局部变量,这两个线程将调用方法分开。您可以像使用 a 那样将这些变量移出为全局变量,或者您可以设置一个结构作为指向包含您要使用/更新的数据。

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

关于c - c同步中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34279701/

相关文章:

c++ - 销毁锁定的互斥锁时 pthread_mutex_destroy 的正确行为是什么

linux - 进程内的线程ID

c - 将 stdout 和 stderr 从 fork 进程复制到文件

c - union 体的默认类型

从二维数组到双指针的转换

C# 多线程 - 'System.Reflection.TargetInvocationException'

java - 我可以在工厂中创建 Callable 并通过调度程序执行它们吗?

c++ - 在 C++ 中将所有 TLS(线程本地存储)变量设置为新的单个值

c++ - 检查当前线程是否为主线程

c - 使用 strtok_r 时我不应该释放 char