例子1:键盘输入的字符会排队,一个一个被线程处理。
#include#include #include using namespace std;char ch = 0;pthread_t tid;void *thread_func(void *arg){ while(true) { ch=getchar(); sleep(1); }}int main(){ //pthread_t tid; if (pthread_create(&tid, NULL, thread_func, NULL) != 0) { cout<<"Create thread error\n"; return -1; } while(1) { if(ch=='p' || ch=='P') { cout<<"Keboard: '"< <<"': print"<
输出结果:
[root@localhost thread]# ./a.out
pKeboard: 'p': printppopKeboard: 'p': printKeboard: 'p': printKeboard: 'p': printpppppqKeboard: 'p': printKeboard: 'p': printKeboard: 'p': printKeboard: 'p': printKeboard: 'p': printKeboard: 'q': exit[root@localhost thread]# ./a.out
pKeboard: 'p': print^C例子2:信号和线程一起的例子
#include#include #include #include using namespace std;char ch = 0;//signalvoid handle_sigint(int){ printf("[singal]: catched ctrl+c\n"); ch='q';}//pthreadpthread_t tid;void *thread_func(void *arg){ while(true) { ch=getchar(); sleep(1); }}int main(){ //signal struct sigaction sig; sig.sa_handler = handle_sigint; sigemptyset(&sig.sa_mask); sig.sa_flags = 0; sigaction(SIGINT, &sig, NULL); //pthread_t if (pthread_create(&tid, NULL, thread_func, NULL) != 0) { cout<<"Create thread error\n"; return -1; } while(1) { if(ch=='p' || ch=='P') { cout<<"Keboard: '"< <<"': print"<
输出结果:
[root@localhost thread]# ./a.out
pKeboard: 'p': printppKeboard: 'p': printKeboard: 'p': printqKeboard: 'q': exit