Example 1: Keyboard input characters are queued and one thread is processed.
#include <iostream>#include<stdio.h>#include<pthread.h>using namespacestd;CharCH =0;p thread_t tid;void*thread_func (void*Arg) { while(true) {ch=GetChar (); Sleep (1); }}intMain () {//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: '"<<ch<<"': Print"<<Endl; CH=0; Continue; }Else if(ch=='Q'|| ch=='Q') {cout<<"Keboard: '"<<ch<<"': Exit"<<Endl; Break; } } return 0;}
Output Result:
[email protected] thread]#./a.out
P
Keboard: ' P ': print
P
P
Op
Keboard: ' P ': print
Keboard: ' P ': print
Keboard: ' P ': print
Pppppq
Keboard: ' P ': print
Keboard: ' P ': print
Keboard: ' P ': print
Keboard: ' P ': print
Keboard: ' P ': print
Keboard: ' Q ': Exit
[email protected] thread]#./a.out
P
Keboard: ' P ': print
^c
Example 2: Examples of signals and threads together
#include <iostream>#include<stdio.h>#include<pthread.h>#include<signal.h>using namespacestd;CharCH =0;//SignalvoidHandle_sigint (int) {printf ("[Singal]: catched ctrl+c\n"); CH='Q';}//pthreadpthread_t tid;void*thread_func (void*Arg) { while(true) {ch=GetChar (); Sleep (1); }}intMain () {//Signal structsigaction 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: '"<<ch<<"': Print"<<Endl; CH=0; Continue; }Else if(ch=='Q'|| ch=='Q') {cout<<"Keboard: '"<<ch<<"': Exit"<<Endl; Break; } } return 0;}
Output Result:
[Email protected] thread]#./a.out
P
Keboard: ' P ': print
P
P
Keboard: ' P ': print
Keboard: ' P ': print
Q
Keboard: ' Q ': Exit
Example of thread response keyboard key