1 #include <stdio.h>
2 #include <pthread.h>
3 #include <string.h>
4
5 //临界资源
6 char str[] = "1234567";
7 int flag = 0; //如果为0,则打印,如为1则逆置
8
9 //互斥锁
10 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
11 //条件变量
12 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
13
14 void* callBack1(void* arg)
15 {
16 while(1)
17 {
18 /***临界区*********/
19 pthread_mutex_lock(&mutex);
20
21 //当flag!=0代表不应该当前线程调度cpu,则立即去休眠,主动放弃cpu资源
22 if(0 != flag)
23 {
24 //当前线程去休眠,等待被唤醒, 并设置唤醒条件
25 pthread_cond_wait(&cond ,&mutex);
26 //被pthread_cond_signal函数唤醒之后后,
27 //尝试上锁。
28 //如果上锁失败,则重新回到cond上继续休眠,等待下次唤醒。
29 //如果上锁成功,则继续往后执行后续代码。
30
31 }
32 if(0 == flag)
33 {
34 printf("%c", str[0]);
35 flag = 1;
36 }
37 //唤醒要运行的线程,线程睡在cond上,则必须以cond的方式唤醒线程
38 pthread_cond_signal(&cond);
39 pthread_mutex_unlock(&mutex);
40 }
41 /***临界区****/
42
43 pthread_exit(NULL);
44 }
45
46 void* callBack2(void* arg)
47 {
48 while(1)
49 {
50 /***临界区*********/
51 pthread_mutex_lock(&mutex);
52
53 //当flag!=1代表不应该当前线程调度cpu,则立即去休眠,主动放弃cpu资源
54 if(1 != flag)
55 {
56 //让当前线程去休眠,等待被唤醒, 并设置唤醒条件
57 pthread_cond_wait(&cond ,&mutex);
58 //被pthread_cond_signal函数唤醒后,
59 //第一件事情是尝试上锁。
60 //如果上锁失败,则重新回到cond上继续休眠,等待下次唤醒。
61 //如果上锁成功,则继续往后执行后续代码。
62 }
63 if(1 == flag)
64 {
65 printf("%c",str[1]);
66 flag = 2;
67 }
68 //唤醒要运行的线程-->由于线程睡在cond上,所以必须以cond的方式唤醒线程
69 pthread_cond_signal(&cond);
70
71 pthread_mutex_unlock(&mutex);
72 /***临界区*********/
73 }
74 pthread_exit(NULL);
75 }
76
77
78 void* callBack3(void* arg)
79 {
80 while(1)
81 {
82 /***临界区*********/
83 pthread_mutex_lock(&mutex);
84
85 //当flag!=1代表不应该当前线程调度cpu,则立即去休眠,主动放弃cpu资源
86 if(2 != flag)
87 {
88 //让当前线程去休眠,等待被唤醒, 并设置唤醒条件
89 pthread_cond_wait(&cond ,&mutex);
90 //被pthread_cond_signal函数唤醒后,
91 //第一件事情是尝试上锁。
92 //如果上锁失败,则重新回到cond上继续休眠,等待下次唤醒。
93 //如果上锁成功,则继续往后执行后续代码。
94 }
95 if(2 == flag)
96 {
97 printf("%c\n",str[2]);
98 flag = 0;
99 }
100 //唤醒要运行的线程-->由于线程睡在cond上,所以必须以cond的方式唤醒线程
101 pthread_cond_signal(&cond);
102
103 pthread_mutex_unlock(&mutex);
104 /***临界区*********/
105 }
106 pthread_exit(NULL);
107 }
108 int main(int argc, const char *argv[])
109 {
110 /*
111 //创建并初始化条件变量
112 if(pthread_cond_init(&cond, NULL) != 0)
113 {
114 perror("pthread_cond_init");
115 return -1;
116 }
117 */
118
119 pthread_t tid1,tid2,tid3;
120 //创建一个线程用于打印1
121 if(pthread_create(&tid1, NULL, callBack1, NULL) != 0)
122 {
123 perror("pthread_create");
124 return -1;
125 }
126
127 //创建一个线程用于打印2
128 if(pthread_create(&tid2, NULL, callBack2, NULL) != 0)
129 {
130 perror("pthread_create");
131 return -1;
132 }
133
134 //创建一个线程用于打印3
135 if(pthread_create(&tid3, NULL, callBack3, NULL) != 0)
136 {
137 perror("pthread_create");
138 return -1;
139 }
140
141 //阻塞等待分支线程退出
142 pthread_join(tid1, NULL);
143 pthread_join(tid2, NULL);
144 pthread_join(tid3, NULL);
145
146 pthread_mutex_destroy(&mutex);
147 pthread_cond_destroy(&cond);
148
149 return 0;
150 }
华清远见2022081班作业
最新推荐文章于 2024-09-16 17:46:36 发布