您的位置:首页 > 其它

两个线程交替打印ABCDEF

2016-10-09 20:47 337 查看
1. 线程交替打印

2. #include <stdio.h>

3. #include <pthread.h>

4. pthread_mutex_t mu;

5. char ch = 'A';

6. void *mythread1()

7. {

8. int i = 0;

9. for(i = 0;i < 3;)

10. {

11. if(pthread_mutex_lock(&mu) == 0)

12. {

13. printf("1 printf %c\n",ch);

14. ch ++;

15. i ++;

16. pthread_mutex_unlock(&mu);

17. }

18. sleep(1);

19. }

20. }

21.

22. void *mythread2()

23. {

24. int i = 0;

25. for(i = 0;i < 3;)

26. {

27. if(pthread_mutex_lock(&mu) == 0)

28. {

29. printf("2 printf %c\n",ch);

30. ch ++;

31. i ++;

32. pthread_mutex_unlock(&mu);

33. }

34. sleep(1);

35. }

36. }

37.

38.

39. int main()

40. {

41. int i = 0;

42. int ret = 0;

43. pthread_t id1,id2;

44. pthread_mutex_init(&mu,NULL);//init the mutex 创建线程互斥锁

45. pthread_mutex_lock(&mu); //先上锁

46.

47. ret = pthread_create(&id1,NULL,(void *)mythread1,NULL);

48. if(ret)

49. {

50. printf("create 1 error\n");

51. return 1;

52. }

53.

54. ret = pthread_create(&id2,NULL,(void *)mythread2,NULL);

55. if(ret)

56. {

57. printf("create 2 error\n");

58. return 1;

59. }

60. pthread_mutex_unlock(&mu);//解锁等待启动

61. pthread_join(id1,NULL);//等待线程结束

62. pthread_join(id2,NULL);

63. return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程