如代码所示
#include<iostream>
#include<unistd.h>
#include<signal.h>
using namespace std;
static int count = 0;
void* myfun(void* arg);
int main()
{
pthread_t pthread = 0;
int ret = pthread_create(&pthread,NULL,myfun,NULL);
//static int count = 0;
char sendbuff[1024] = {0};
while( fgets(sendbuff,sizeof(sendbuff),stdin)!= NULL){
count ++;
}
}
void* myfun(void *arg){
while(1){
sleep(1);
cout << "count : "<<count << endl;
}
}
进程拥有两个线程:主线程A,子线程B
主线程:创建子线程,处理来自stdin的字符
子线程:里面是一个死循环,睡眠一秒钟,然后输出静态count值。
fgets(),获取stdin的时候是等待io输入的一个状态,线程是阻塞的。运行过程有两种情况:
- 阻塞线程
- 接受了输入,走while循环体里面的逻辑,然后接着阻塞
该博客讨论了一个进程中的主线程与子线程协同工作的示例。主线程创建并管理一个子线程,主线程从`stdin`读取输入,而子线程在一个无限循环中每秒打印静态变量`count`的值。`fgets()`的使用导致主线程在等待用户输入时被阻塞。博客突出了多线程同步和I/O操作的概念。
1597

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



