当前位置: 技术问答>linux和unix
多线程编程,如何用一个线程模拟键盘的输入呀?
来源: 互联网 发布时间:2016-01-04
本文导语: 原程序是2个线程:A与B(为了便于描述,假设嗬), B控制A的暂停与继续。 B线程在不断等待键盘输入: while(1) { key_val = keyhit(); if (key_val == 'p') { printf("Pause...n"); ... } ...
原程序是2个线程:A与B(为了便于描述,假设嗬),
B控制A的暂停与继续。
B线程在不断等待键盘输入:
while(1)
{
key_val = keyhit();
if (key_val == 'p')
{
printf("Pause...n");
...
}
if (key_val == 'c')
{
printf("Continue...n");
...
}
}
key_val是全局变量。
现在增加一个线程C,socket编程,用于远程控制。
在一系列的
createsocket();
bind();
listen();
accept();
recv(buff);
之后,用printf("%sn", buff);可以打印出接收到的信息。
不过,key_val = buff[0]; //buff是个数组。
并没有成功地模拟B线程,从而达到控制A线程的目的。
不知道为什么。全局变量应该谁都可以操作吧,怎么不奏效呢?
B控制A的暂停与继续。
B线程在不断等待键盘输入:
while(1)
{
key_val = keyhit();
if (key_val == 'p')
{
printf("Pause...n");
...
}
if (key_val == 'c')
{
printf("Continue...n");
...
}
}
key_val是全局变量。
现在增加一个线程C,socket编程,用于远程控制。
在一系列的
createsocket();
bind();
listen();
accept();
recv(buff);
之后,用printf("%sn", buff);可以打印出接收到的信息。
不过,key_val = buff[0]; //buff是个数组。
并没有成功地模拟B线程,从而达到控制A线程的目的。
不知道为什么。全局变量应该谁都可以操作吧,怎么不奏效呢?
|
please use pthread_mutex_t to synchronize threads, to protect the global vairable from inconsistent accessing.
Global variable can be accessed by any threads. but the problem occurs when one thread write the variable, but other one read the variable. then every thing is messed up.
For example, thread B read the key_val, and it's value is 'p' to pause the thread A. but that time thread C change the key_val to "continue" which means to continue thread A.
you need synchronize the threads.
Global variable can be accessed by any threads. but the problem occurs when one thread write the variable, but other one read the variable. then every thing is messed up.
For example, thread B read the key_val, and it's value is 'p' to pause the thread A. but that time thread C change the key_val to "continue" which means to continue thread A.
you need synchronize the threads.
|
key_val = keyhit();
因为你每次都在修改它
因为你每次都在修改它
|
linux的吗?