Linux 多线程编程—使用条件变量实现循环打印

简介: 编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。 使用条件变量来实现:   1 #include 2 #include 3 #include 4 st...

编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。

使用条件变量来实现:

 

 1 #include <pthread.h>
 2 #include <stdio.h>
 3 #include <unistd.h>
 4 static pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;
 5 
 6 static pthread_cond_t condA ;
 7 static pthread_cond_t condB ;
 8 static pthread_cond_t condC ;
 9 
10 
11 void* threadA(void *arg)
12 {
13 int a =10;
14 while(a--)
15 {
16 //sleep(2);
17 //printf("A begin.\n");
18 pthread_mutex_lock(&mtx);
19 //printf("A wait.\n");
20 pthread_cond_wait(&condC,&mtx);
21 printf("A.\n");
22 pthread_mutex_unlock(&mtx);
23 pthread_cond_signal(&condA);
24 }
25 }
26 
27 void* threadB(void *arg)
28 {
29 int b=10;
30 while(b--)
31 {
32 //sleep(2);
33 //printf("B begin.\n");
34 pthread_mutex_lock(&mtx);
35 //printf("B wait.\n");
36 pthread_cond_wait(&condA,&mtx);
37 printf("B.\n");
38 pthread_mutex_unlock(&mtx);
39 pthread_cond_signal(&condB);
40 }
41 }
42 
43 void* threadC(void *arg)
44 
45 {
46 int c=10;
47 while(c--)
48 {
49 //sleep(2);
50 //printf("C begin.\n");
51 pthread_mutex_lock(&mtx);
52 //printf("C wait.\n");
53 pthread_cond_wait(&condB,&mtx);
54 printf("C.\n");
55 pthread_mutex_unlock(&mtx);
56 pthread_cond_signal(&condC);
57 }
58 }
59 int main (void *arg)
60 {
61 pthread_t tidA;
62 pthread_t tidB;
63 pthread_t tidC;
64 pthread_cond_init(&condA,NULL);
65 pthread_cond_init(&condB,NULL);
66 pthread_cond_init(&condC,NULL);
67 pthread_create(&tidA,NULL,&threadA,NULL);
68 pthread_create(&tidB,NULL,&threadB,NULL);
69 pthread_create(&tidC,NULL,&threadC,NULL);
70 
71 printf("main begin..\n");
72 sleep(4);
73 pthread_cond_signal(&condC);
74 
75 pthread_join(tidA,NULL);
76 pthread_join(tidB,NULL);
77 pthread_join(tidC,NULL);
78 
79 return 0;
80 }

 


作者: HarlanC

博客地址: http://www.cnblogs.com/harlanc/
个人博客: http://www.harlancn.me/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接

如果觉的博主写的可以,收到您的赞会是很大的动力,如果您觉的不好,您可以投反对票,但麻烦您留言写下问题在哪里,这样才能共同进步。谢谢!

目录
相关文章
|
2天前
|
Linux API
|
2天前
|
Unix Linux 调度
linux线程与进程的区别及线程的优势
linux线程与进程的区别及线程的优势
|
3天前
|
存储 算法 Linux
【Linux】线程的内核级理解&&详谈页表以及虚拟地址到物理地址之间的转化
【Linux】线程的内核级理解&&详谈页表以及虚拟地址到物理地址之间的转化
|
4天前
|
Linux Perl
Linux|了解如何使用 awk 内置变量
Linux|了解如何使用 awk 内置变量
11 1
|
6天前
|
算法 Java Linux
【探索Linux】P.23(线程池 —— 简单模拟)
【探索Linux】P.23(线程池 —— 简单模拟)
9 0
|
6天前
|
存储 安全 Java
【探索Linux】P.21(多线程 | 线程同步 | 条件变量 | 线程安全)
【探索Linux】P.21(多线程 | 线程同步 | 条件变量 | 线程安全)
11 0
|
6天前
|
算法 安全 Linux
【探索Linux】P.20(多线程 | 线程互斥 | 互斥锁 | 死锁 | 资源饥饿)
【探索Linux】P.20(多线程 | 线程互斥 | 互斥锁 | 死锁 | 资源饥饿)
11 0
|
6天前
|
存储 安全 Linux
【探索Linux】P.19(多线程 | 线程的概念 | 线程控制 | 分离线程)
【探索Linux】P.19(多线程 | 线程的概念 | 线程控制 | 分离线程)
7 0
|
2天前
|
安全 网络协议 Linux
linux必学的60个命令
Linux是一个功能强大的操作系统,提供了许多常用的命令行工具,用于管理文件、目录、进程、网络和系统配置等。以下是Linux必学的60个命令的概览,但请注意,这里可能无法列出所有命令的完整语法和选项,仅作为参考