免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1342 | 回复: 2

多线程的问题,刚刚开始学编多线程 [复制链接]

论坛徽章:
0
发表于 2012-04-10 19:51 |显示全部楼层
  1 #include <stdio.h>
  2 #include <string.h>
  3 #include <pthread.h>
  4 #include <unistd.h>
  5 #include <stdlib.h>
  6 #include <signal.h>
  7
  8 int  iCOUNT = 0;
  9 pthread_mutex_t  counter_mutex = PTHREAD_MUTEX_INITIALIZER;
10 void pthread_1 (const char *s)
11 {
12   int i= 0;
13   for ( i ; i<3;i++)
14     {
15       pthread_mutex_lock(&counter_mutex);
16       iCOUNT ++;
17       pthread_mutex_lock(&counter_mutex);
18       sleep(2);
19       printf("\n This  is 1   iCOUNT = [%d]\n",iCOUNT);
20     }
21 }
22
23 void   pthread_2( int *a)
24 {
25   int i = 0;
26   for( i ;i<3;i++ )
27     {
28       pthread_mutex_lock(&counter_mutex);
29       iCOUNT  ++;
30       pthread_mutex_unlock(&counter_mutex);
31       sleep(2);
32       printf("\n This  is 2   iCOUNT = [%d]\n",iCOUNT);
33     }
34
35
36 }
37 int main(int argc, char **argv)
38 {
39   int   i, ret1, ret2 ,ret3;
40   i = 0;
41   int  a =123;
42   pthread_t  tnid;
43   pthread_t  pnid;
44   printf ("hellow\n");
45   ret1 = pthread_create(&tnid,NULL,(void *)pthread_1,"hello,world");
46   ret2 = pthread_create(&pnid,NULL,(void *)pthread_2,&a);
47
48   for( i ;i<3;i++ )
49     {
50
51       pthread_mutex_lock(&counter_mutex);
52       iCOUNT ++;
53       pthread_mutex_unlock(&counter_mutex);
54       printf("\n This  is main   iCOUNT = [%d]\n",iCOUNT);
55     }
56   pthread_join(tnid,NULL);
57   pthread_join(pnid,NULL);
58
59
60   return  ret1;
61 }

起了2个线程, 每个线程 用了一把锁,  但是程序 运行,就 死锁在那里, 由于刚刚自己学着编写的程序, 不知道原因,自己再找, 请大侠指导一下~~~


论坛徽章:
0
发表于 2012-04-10 19:54 |显示全部楼层
10 void pthread_1 (const char *s)
11 {
12   int i= 0;
13   for ( i ; i<3;i++)
14     {
15       pthread_mutex_lock(&counter_mutex);
16       iCOUNT ++;
17       pthread_mutex_lock(&counter_mutex);
18       sleep(2);
19       printf("\n This  is 1   iCOUNT = [%d]\n",iCOUNT);
20     }
21 }
在这个线程中调用了2次pthread_mutex_lock,当然会死锁了

论坛徽章:
0
发表于 2012-04-10 19:57 |显示全部楼层
谢谢,汗颜啊, 自己的程序都没有看仔细~~谢谢了~~  刚才用的 p  赋值~~

这些很初级的问题,怕浪费大家时间,但是自己写的,真的 一开始很难发现 错误~~ 还要谢谢你了~~
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP