0

最初のスレッドが作成され、他のスレッドの実行を許可せずに 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
4

2 に答える 2

2

この呼び出し:

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

直前の行で作成したスレッドが終了するまで待機し、 Produce() スレッドが終了しないため、スレッドは 1 つだけ作成されます。

于 2013-02-24T20:18:25.550 に答える
1

pthread_joinスレッドが終了するのを待つため、永遠に待機します。

于 2013-02-24T20:18:44.860 に答える