首页 > 代码库 > 线程响应键盘按键的例子
线程响应键盘按键的例子
例子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
线程响应键盘按键的例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。