码迷,mamicode.com
首页 > 编程语言 > 详细

线程响应键盘按键的例子

时间:2014-09-05 14:07:31      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   ar   div   cti   sp   

例子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;

//signal
void handle_sigint(int)
{
        printf("[singal]: catched ctrl+c\n");
        ch=q;
}

//pthread
pthread_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

线程响应键盘按键的例子

标签:style   blog   color   os   io   ar   div   cti   sp   

原文地址:http://www.cnblogs.com/jacklikedogs/p/3957828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!