首页 > 代码库 > 线程响应键盘按键的例子

线程响应键盘按键的例子

例子1:键盘输入的字符会排队,一个一个被线程处理。

#include <iostream>#include <stdio.h>#include <pthread.h>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: ‘"<<ch<<"‘: print"<<endl;                        ch=0;                        continue;                }else if(ch==q || ch==Q)                {                        cout<<"Keboard: ‘"<<ch<<"‘: exit"<<endl;                        break;                }        }        return 0;}

 

输出结果:

[root@localhost 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

[root@localhost thread]# ./a.out
p
Keboard: ‘p‘: print
^C

例子2:信号和线程一起的例子

#include <iostream>#include <stdio.h>#include <pthread.h>#include <signal.h>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: ‘"<<ch<<"‘: print"<<endl;                        ch=0;                        continue;                }else if(ch==q || ch==Q)                {                        cout<<"Keboard: ‘"<<ch<<"‘: exit"<<endl;                        break;                }        }        return 0;}

输出结果:

[root@localhost thread]# ./a.out
p
Keboard: ‘p‘: print
p
p
Keboard: ‘p‘: print
Keboard: ‘p‘: print
q
Keboard: ‘q‘: exit

线程响应键盘按键的例子