两个线程交替打印ABCDEF

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值