Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1121501
  • 博文数量: 141
  • 博客积分: 2853
  • 博客等级: 少校
  • 技术积分: 2266
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-04 12:03
文章分类

全部博文(141)

文章存档

2014年(3)

2013年(12)

2012年(126)

分类: 嵌入式

2012-06-27 14:59:46

不得不说今天又遇到了一件坑爹的事情,linux下用多线程实现答应ABBABBABBABBABB....代码如下:红色部分为啃爹的部分!

点击(此处)折叠或打开

  1. #include
  2. #include
  3. #include
  4. #include
  5. #include
  6. #include
  7. #include
  8. #include
  9. sem_t sem;
  10. void *thrd_fun1(void *arg)
  11. {
  12. int thrd_num=(int)arg;
  13. while(1)
  14. {
  15. printf("A\n");//当驱动\n换行符会出现程序卡死现象,目前还不清楚为什么!
  16. sem_post(&sem);
  17. sleep(2);
  18. }
  19. pthread_exit(NULL);
  20. }
  21. void *thrd_fun2(void *arg)
  22. {
  23. int thrd_num=(int)arg;
  24. int i;
  25. while(1)
  26. {
  27. sem_wait(&sem);
  28. printf("B\n");
  29. sleep(1);
  30. printf("B\n");
  31. sleep(1);
  32. }
  33. pthread_exit(NULL);
  34. }
  35. int main(void)
  36. {
  37. pthread_t thread[2];
  38. int no=0,res;
  39. void *thrd_ret;
  40. sem_init(&sem,0,0);
  41. res=pthread_create(&thread[0],NULL,thrd_fun1,(void*)no);
  42. if(res!=0)
  43. {
  44. printf("Create thread 1 failed\n");
  45. exit(res);
  46. }
  47. res=pthread_create(&thread[1],NULL,thrd_fun2,(void*)no);
  48. if(res!=0)
  49. {
  50. printf("Create thread 1 failed\n");
  51. exit(res);
  52. }
  53. for(no=0;no<2;no++)
  54. {
  55. res =pthread_join(thread[no],&thrd_ret);
  56. if(!res)
  57. {
  58. printf("Thread %d exit\n",no);
  59. }
  60. else
  61. {
  62. printf("Thread %d exit failed\n",no);
  63. }
  64. }
  65. return 0;
  66. }

阅读(2465) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~