我有pthread_create
的问题。我想创建一个跟踪键盘按钮的线程,例如,当我按空格键时,程序将中止主循环。
这是我的代码(创建一个线程):
void check_button_code(int *btn);
// main
pthread_t trd;
int btn = 1;
pthread_create(&trd,NULL,check_button_code, &btn);
打破行动
void check_button_code(int *btn) {
int a;
printf("Press space to pause\n.");
while (1) {
a = getchar();
if (a == 32) {
*btn = 0;
break;
} else {
printf("error %d\n", a);
}
}
printf("zatrzymane\n");
}
预先感谢您的帮助。
首先,您必须等待线程完成。添加到main,返回之前,
pthread_join(trd, NULL);
否则,主线程在创建线程后立即结束。你的main()函数应该是这样的
int main() {
pthread_t trd;
int btn = 1;
pthread_create(&trd,NULL,(void*)check_button_code, &btn);
pthread_join(trd, NULL);
return 0;
}
然后getchar()
将不会渲染char,直到按下CR。因此,要使线程读取空格,您必须输入空格,然后按ENTER键。
要反过来处理角色,请参阅this answer, for instance。这样,在等待按下输入之前将处理空间。