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

如何根据用户输入创建多线程?是否需用指针数组初始化线程?

问题解答

首先明确结论:不需要用指针数组,直接申请pthread_t类型的动态数组即可完成线程ID的存储与后续操作。

现有代码的问题

  • 存在拼写错误:你定义的变量是noOfPoducers(少了字母r),但循环里用的是noOfProducers,运行会直接报错。
  • 你把pthread_t prodId1[1]定义在for循环内部,属于循环体的局部变量,每次循环结束后该变量就会被销毁,你后续无法拿到已创建线程的ID执行pthread_join等操作,完全不具备可用性。

正确实现方案

你只需要根据命令行传入的生产者、消费者数量,动态申请对应长度的pthread_t数组即可,示例代码如下:

#include <pthread.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{   
    // 先判断参数数量是否合法,避免段错误
    if(argc < 4) return 1;
    int sleepTime = atoi(argv[1]);
    int noOfProducers = atoi(argv[2]);
    int noOfConsumers = atoi(argv[3]);

    // 动态申请存储线程ID的数组,不需要指针数组
    pthread_t *prod_ids = malloc(noOfProducers * sizeof(pthread_t));
    pthread_t *cons_ids = malloc(noOfConsumers * sizeof(pthread_t));

    // 创建生产者线程
    for(int i = 0; i < noOfProducers; i++){
        // 第三个参数是你实现的生产者线程函数,第四个是传给线程的参数
        pthread_create(&prod_ids[i], NULL, producer_routine, NULL);
    }
    // 创建消费者线程逻辑同上,用cons_ids数组即可

    // 后续可以用数组里的ID等待线程执行结束
    for(int i = 0; i < noOfProducers; i++){
        pthread_join(prod_ids[i], NULL);
    }

    // 最后释放申请的数组内存
    free(prod_ids);
    free(cons_ids);
    return 0;
}

额外说明

如果你的C版本支持变长数组(VLA),且生产者/消费者数量不会特别大不会导致栈溢出,也可以直接在栈上定义变长数组:

pthread_t prod_ids[noOfProducers];

这种方式不需要手动free,但要注意栈空间大小限制,线程数量大的时候还是用malloc更稳妥。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:06:03