getchar在Linux多線(xiàn)程編程中的應(yīng)用

小樊
83
2024-09-06 21:26:45

getchar() 是一個(gè)C語(yǔ)言庫(kù)函數(shù),用于從標(biāo)準(zhǔn)輸入(通常是鍵盤(pán))讀取一個(gè)字符

在Linux多線(xiàn)程編程中,你可以在一個(gè)單獨(dú)的線(xiàn)程里使用 getchar(),以便在其他線(xiàn)程執(zhí)行任務(wù)時(shí)接收用戶(hù)輸入。這種方法可以讓你的程序在執(zhí)行復(fù)雜任務(wù)時(shí)保持對(duì)用戶(hù)輸入的響應(yīng)。

下面是一個(gè)簡(jiǎn)單的示例,展示了如何在Linux多線(xiàn)程編程中使用 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;

    // 創(chuàng)建輸入線(xiàn)程
    if (pthread_create(&input_tid, NULL, input_thread, NULL) != 0) {
        perror("Failed to create input thread");
        exit(1);
    }

    // 創(chuàng)建工作線(xiàn)程
    if (pthread_create(&worker_tid, NULL, worker_thread, NULL) != 0) {
        perror("Failed to create worker thread");
        exit(1);
    }

    // 等待線(xiàn)程結(jié)束
    pthread_join(input_tid, NULL);
    pthread_join(worker_tid, NULL);

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

在這個(gè)示例中,我們創(chuàng)建了兩個(gè)線(xiàn)程:一個(gè)用于接收用戶(hù)輸入,另一個(gè)用于執(zhí)行一些模擬工作。當(dāng)用戶(hù)按下 ‘q’ 鍵時(shí),程序?qū)⑼顺觥?/p>

0