You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

线程创建后如何获取用户输入?电梯模拟器输入交互问题

问题分析

你的代码出现该问题有几个核心原因:

  1. 标准输出缓冲机制:printf默认采用行缓冲模式,输出内容会先暂存到缓冲区,未触发刷新时不会立即显示到终端,多个线程的提示信息会批量输出。
  2. 线程IO竞争:多线程启动后,操作系统调度会优先让各线程执行完printf语句,之后才集中处理scanf输入,导致提示批量打印后才接收输入。
  3. 全局变量冲突:所有线程共用全局变量user_input,即便实现即时输入,后续线程的输入也会覆盖之前的值,数据完全混乱。
  4. 主线程未等待子线程:主线程创建线程后直接调用pthread_exit,虽子线程会继续运行,但主线程退出可能导致终端IO行为异常。
修复后的代码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define NUM_THREAD 6

// 定义线程参数结构体,为每个线程存储独立的目标楼层
typedef struct {
    long tid;
    int dest_floor;
} ThreadData;

pthread_mutex_t io_mutex = PTHREAD_MUTEX_INITIALIZER;

void *passengers(void *arg) {
    ThreadData *data = (ThreadData *)arg;
    
    // 加锁确保提示与输入操作的原子性,避免线程打断
    pthread_mutex_lock(&io_mutex);
    
    printf("Passenger %ld Kindly select your floor number: ", data->tid);
    fflush(stdout); // 强制刷新输出缓冲区,让提示立即显示
    
    scanf("%d", &data->dest_floor);
    printf("Passenger %ld selected floor %d\n", data->tid, data->dest_floor);
    
    pthread_mutex_unlock(&io_mutex);
    
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[NUM_THREAD];
    ThreadData thread_data[NUM_THREAD];
    int th;

    for (long t = 1; t < NUM_THREAD; t++) {
        thread_data[t].tid = t;
        thread_data[t].dest_floor = 0;
        
        th = pthread_create(&threads[t], NULL, passengers, (void *)&thread_data[t]);
        if (th != 0) {
            printf("ERROR Creating Thread %ld\n", t);
            exit(-1);
        }
    }

    // 等待所有子线程执行完成
    for (long t = 1; t < NUM_THREAD; t++) {
        pthread_join(threads[t], NULL);
        printf("Main: Passenger %ld's target floor is %d\n", t, thread_data[t].dest_floor);
    }

    pthread_mutex_destroy(&io_mutex);
    return 0;
}
关键修复点
  • 互斥锁保护IO流程:用互斥锁包裹每个线程的提示、输入操作,确保同一时间只有一个线程操作终端,避免提示与输入交叉。
  • 强制刷新输出缓冲区:调用fflush(stdout)让printf的内容立即显示到终端,不再依赖缓冲触发条件。
  • 独立线程数据存储:通过结构体ThreadData为每个线程分配独立的目标楼层变量,彻底解决全局变量冲突问题。
  • 主线程等待子线程:使用pthread_join逐个等待所有子线程完成,确保所有输入处理完毕后主线程才退出。
运行效果

修复后程序会按以下逻辑执行:

Passenger 1 Kindly select your floor number: 3
Passenger 1 selected floor 3
Main: Passenger 1's target floor is 3
Passenger 2 Kindly select your floor number: 5
Passenger 2 selected floor 5
Main: Passenger 2's target floor is 5
...以此类推

内容的提问来源于stack exchange,提问作者Weke Moyosore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 23:20:36