温馨提示×

getchar在Linux多线程编程中的应用

小樊
83
2024-09-06 21:26:45
栏目: 智能运维

getchar() 是一个C语言库函数,用于从标准输入(通常是键盘)读取一个字符

在Linux多线程编程中,你可以在一个单独的线程里使用 getchar(),以便在其他线程执行任务时接收用户输入。这种方法可以让你的程序在执行复杂任务时保持对用户输入的响应。

下面是一个简单的示例,展示了如何在Linux多线程编程中使用 getchar()

#include<stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

void* input_thread(void *arg) {
    char c;
    printf("Press 'q' to quit\n");
    while ((c = getchar()) != 'q') {
        printf("You pressed: %c\n", c);
    }
    return NULL;
}

void* worker_thread(void *arg) {
    int i;
    for (i = 0; i < 5; i++) {
        printf("Worker thread: Doing some work...\n");
        sleep(1);
    }
    return NULL;
}

int main() {
    pthread_t input_tid, worker_tid;

    // 创建输入线程
    if (pthread_create(&input_tid, NULL, input_thread, NULL) != 0) {
        perror("Failed to create input thread");
        exit(1);
    }

    // 创建工作线程
    if (pthread_create(&worker_tid, NULL, worker_thread, NULL) != 0) {
        perror("Failed to create worker thread");
        exit(1);
    }

    // 等待线程结束
    pthread_join(input_tid, NULL);
    pthread_join(worker_tid, NULL);

    printf("All threads finished.\n");
    return 0;
}

在这个示例中,我们创建了两个线程:一个用于接收用户输入,另一个用于执行一些模拟工作。当用户按下 ‘q’ 键时,程序将退出。

0