一个线程竞争的问题

 下面这个程序存在竞争,当对等线程执行 int myid = *((int *)argv)  前,如果主线程先执行了 i++,那么对等线程的执行结果是不正确。

  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3.   
  4. #define N 100  
  5.   
  6. void *thread(void *argv)  
  7. {  
  8.     int myid = *((int *)argv);  
  9.     printf("hello from thread %d\n", myid);  
  10.     return NULL;  
  11. }  
  12.   
  13. int main(int argc, char **argv)  
  14. {  
  15.     pthread_t tid[N];  
  16.     int i;  
  17.     for(i = 0; i < N; i++)  
  18.         pthread_create(&tid[i], NULL, thread, &i);  
  19.     for(i = 0; i < N; i++)  
  20.         pthread_join(tid[i], NULL);  
  21.     return 0;  
  22. }  
        《深入理解计算机系统》一书给出了两种方法,一是动态为每一个 id 分配内存,并且传递给线程一个指向这个块的指针,代码如下:

  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <stdlib.h>  
  4. #define N 100  
  5.   
  6. void *thread(void *argv)  
  7. {  
  8.     int myid = *((int *)argv);  
  9.     free(argv);   //释放空间  
  10.     printf("hello from thread %d\n", myid);  
  11.     return NULL;  
  12. }  
  13.   
  14. int main(int argc, char **argv)  
  15. {  
  16.     pthread_t tid[N];  
  17.     int i, *p;  
  18.     for(i = 0; i < N; i++)  
  19.     {  
  20.         p = malloc(sizeof(int)); //动态为每一个 id 分配内存  
  21.         *p = i;  
  22.         pthread_create(&tid[i], NULL, thread, p);  
  23.     }  
  24.     for(i = 0; i < N; i++)  
  25.         pthread_join(tid[i], NULL);  
  26.     return 0;  
  27. }  
        这种方法的缺点就是需要在对等线程中释放空间,另一种方法是利用强制转换,它的缺点是假设指针至少和int一样大。代码如下:

  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #define N 100  
  4.   
  5. void *thread(void *argv)  
  6. {  
  7.     int myid = (int) argv;  
  8.     printf("hello from thread %d\n", myid);  
  9.     return NULL;  
  10. }  
  11.   
  12. int main(int argc, char **argv)  
  13. {  
  14.     pthread_t tid[N];  
  15.     int i;  
  16.     for(i = 0; i < N; i++)  
  17.         pthread_create(&tid[i], NULL, thread, (void *)i);  
  18.     for(i = 0; i < N; i++)  
  19.         pthread_join(tid[i], NULL);  
  20.     return 0;  
  21. }  
       本人享有博客文章的版权,转载请标明出处 http://blog.youkuaiyun.com/wuzhekai1985
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值