C++ pthreads仅创建一个线程
我不明白为什么创建第一个线程并在while循环中运行,而不允许其他线程也运行。我确实在它进入睡眠状态之前解锁了它,以便创建其他线程。我想我必须一次创建所有线程,这样才能工作,但这难道不会使它成为非线程安全的吗 大体上:C++ pthreads仅创建一个线程,c++,c,thread-safety,pthreads,C++,C,Thread Safety,Pthreads,我不明白为什么创建第一个线程并在while循环中运行,而不允许其他线程也运行。我确实在它进入睡眠状态之前解锁了它,以便创建其他线程。我想我必须一次创建所有线程,这样才能工作,但这难道不会使它成为非线程安全的吗 大体上: Producer *producers[NUM_PTHREADS]; for (i = 0; i < NUM_PTHREADS; i++) { tn[i] = i; producers[i] = new Producer(producer
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++;
}
示例输出:
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);
等待直到您在该行上创建的线程结束,并且product()线程永远不会结束,因此您将只创建一个线程。此调用:
pthread_join(*(producers[i]->getThread()),NULL);
等待直到您在该行上创建的线程结束,并且product()线程永远不会结束,因此您将只创建一个线程。
pthread\u join
等待线程完成,因此它将永远等待。pthread\u join
等待线程完成,因此它将永远等待。,我应该把这条线移到哪里?在创建后它自己的for循环中?或者,我甚至不需要它吗?@dff如果你想等待所有线程完成,那么是的,再做一个循环。这完全有意义。非常感谢你!如果可能的话,我会接受的。我应该把这条线移到哪里?在创建后它自己的for循环中?或者,我甚至不需要它吗?@dff如果你想等待所有线程完成,那么是的,再做一个循环。这完全有意义。非常感谢你!如果可能的话,我会接受的