多线程编程:从基础到高级应用
1. 字符计数线程示例
1.1 代码运行与功能
首先,我们来看一个简单的字符计数线程示例。通过以下命令编译和运行代码:
$ cc −D_REENTRANT thread5.c −o thread5 −lpthread
$ ./thread5
运行程序后,会提示输入文本,输入 end 结束输入。示例运行结果如下:
Input some text. Enter 'end' to finish
Whit
You input 4 characters
The Crow Road
You input 13 characters
end
Waiting for thread to finish...
Thread joined
1.2 代码实现与原理
代码中,我们首先声明了互斥锁、工作区域和一个额外的变量 time_to_exit :
pthread_mutex_t work_mutex; /* protects both work_area and time_to_exit */
#define WORK_SIZE 1024
char work_area[WORK_SIZE];
int time_to_exit = 0;
接着初始化互斥锁:
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



