pthreads只创建一个线程

时间:2013-02-24 20:16:23

标签: 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_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

2 个答案:

答案 0 :(得分:2)

这个电话:

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

等到你在它前面的行上创建的线程结束,你的produce()线程永远不会结束,所以你只会创建一个线程。

答案 1 :(得分:1)

pthread_join等待一个线程完成,所以它会永远等待。