我不明白为什么创建第一个线程并通过 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