如代码所示
#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循环体里面的逻辑,然后接着阻塞