getchar 是一个 C 语言库函数,用于从标准输入(通常是键盘)读取一个字符。在多线程环境中使用 getchar 时,需要注意线程安全和同步问题。以下是一些建议:
getchar 的调用。当一个线程正在使用 getchar 时,其他线程将被阻塞,直到互斥锁被释放。这可以确保在同一时刻只有一个线程能够调用 getchar。#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t lock;
void* thread_func(void* arg) {
    char ch;
    pthread_mutex_lock(&lock);
    ch = getchar();
    pthread_mutex_unlock(&lock);
    // 处理字符 ch
    return NULL;
}
int main() {
    pthread_t threads[4];
    pthread_mutex_init(&lock, NULL);
    for (int i = 0; i < 4; ++i) {
        pthread_create(&threads[i], NULL, thread_func, NULL);
    }
    for (int i = 0; i < 4; ++i) {
        pthread_join(threads[i], NULL);
    }
    pthread_mutex_destroy(&lock);
    return 0;
}
getchar 的线程。#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
int data = 0;
void* thread_func(void* arg) {
    char ch;
    pthread_mutex_lock(&lock);
    while (data == 0) {
        pthread_cond_wait(&cond, &lock);
    }
    ch = data;
    data = 0;
    pthread_mutex_unlock(&lock);
    // 处理字符 ch
    return NULL;
}
void input_func() {
    char ch;
    pthread_mutex_lock(&lock);
    ch = getchar();
    data = ch;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&lock);
}
int main() {
    pthread_t threads[4];
    pthread_mutex_init(&lock, NULL);
    pthread_cond_init(&cond, NULL);
    for (int i = 0; i < 4; ++i) {
        pthread_create(&threads[i], NULL, thread_func, NULL);
    }
    for (int i = 0; i < 4; ++i) {
        input_func();
    }
    for (int i = 0; i < 4; ++i) {
        pthread_join(threads[i], NULL);
    }
    pthread_mutex_destroy(&lock);
    pthread_cond_destroy(&cond);
    return 0;
}
这两种方法都可以确保在多线程环境中安全地使用 getchar。你可以根据你的需求和场景选择合适的方法。