c - 使用 pthread_create 在 C 中创建线程

标签 c

pthread_create 有问题。我想创建一个线程来跟踪键盘按钮,例如,当我按下空格键时,程序会中止主循环。

这是我的代码(创建一个线程):

void check_button_code(int *btn);
     // main 
    pthread_t trd;
    int btn = 1;
    pthread_create(&trd,NULL,check_button_code, &btn);

中断 Action

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() 将不会呈现字符,直到按下 CR。因此,要使线程读取一个空格,您必须输入一个空格,然后按 ENTER

要实时处理字符,请参阅 this answer, for instance .这样,在等待按下 enter 之前,将处理 space

关于c - 使用 pthread_create 在 C 中创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47405603/

相关文章:

c - 位运算符。十进制和十六进制

c - 无法在/usr/share中创建目录

javascript - 从 JavaScript 调用 C 共享库 API(在 .so lib 中)

for循环中的C基本增加/减少问题

使用 c 程序更改应用程序核心转储目录

c++ - 在运算符之间添加间距的目的是什么?

使用 for 循环与结构指针复制数组元素

c - 将 time_t 设置为毫秒

c++ - 在内核空间调用 NtQuerySystemInformation

c - 当您使用 void (*)() 指针调用返回 int 的函数时会发生什么?