gpt4 book ai didi

c++ - pthreads 只创建一个线程

转载 作者:太空宇宙 更新时间:2023-11-04 07:29:37 26 4
gpt4 key购买 nike

我不明白为什么第一个线程被创建并通过 while 循环运行而不允许其他线程也运行。我确实在它进入休眠状态之前专门解锁,以便创建其他线程。我认为我必须一次创建所有线程才能使其工作,但这不会使其成为非线程安全的吗?

主要内容:

Producer *producers[NUM_PTHREADS];
for (i = 0; i < NUM_PTHREADS; i++) {
tn[i] = i;
producers[i] = new Producer(producer_id);
pthread_create(producers[i]->getThread(),NULL,produce,producers[i]);
pthread_join(*(producers[i]->getThread()),NULL);
producer_id++;
}

从 pthread_create 运行:

void *produce(void* elem){
Producer *producer;
producer = (Producer*)elem;
while(1){
pthread_mutex_lock(&pmutex);
printf("Hi, this is thread %d\n",producer->getId());
producer->makeProduct(product_id);
product_id++;
printf("Made product with thread: %d, product_id: %d\n",producer->getId(),product_id);
pthread_mutex_unlock(&pmutex);
producer->sleep();
}
}

示例输出:

Hi, this is thread 0
Made product with thread: 0, product_id: 1
Hi, this is thread 0
Made product with thread: 0, product_id: 2
Hi, this is thread 0
Made product with thread: 0, product_id: 3
Hi, this is thread 0
Made product with thread: 0, product_id: 4
Hi, this is thread 0
Made product with thread: 0, product_id: 5
Hi, this is thread 0
Made product with thread: 0, product_id: 6
Hi, this is thread 0
Made product with thread: 0, product_id: 7
Hi, this is thread 0
Made product with thread: 0, product_id: 8
Hi, this is thread 0
Made product with thread: 0, product_id: 9
Hi, this is thread 0
Made product with thread: 0, product_id: 10

最佳答案

这个调用:

 pthread_join(*(producers[i]->getThread()),NULL);

一直等到您在它之前的行上创建的线程结束,并且您的 produce() 线程永远不会结束,因此您只会创建 1 个线程。

关于c++ - pthreads 只创建一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15056152/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com