Я создаю 10 потоков. Каждый поток выполнит какую-то задачу. Есть 7 задач. Поскольку количество задач меньше количества потоков, всегда будет 3 потока, которые спят и ничего не делают.
Мой основной поток должен дождаться завершения задач и завершиться только после того, как все задачи будут выполнены (т.е. когда поток завершится). Я жду в течение l oop и звоню pthread_join
, но с 3 спящими потоками, как я могу разбудить их и заставить их выйти?
Вот что я делаю сейчас.
// thread handler function, called when the thread is created
void* handler_func(void* arg) {
while(true){
pthread_mutex_lock(&my_queue_mutex);
while(my_queue_is_empty()) {
pthread_cond_wait(&my_cond_var, &my_queue_mutex);
}
item = get_item_from_queue();
pthread_mutex_unlock(&my_queue_mutex);
}
pthread_exit(NULL);
}
int total_threads_to_create = 10;
int total_requests_to_make = 7;
pthread_t threads[total_threads_to_create];
for(int i = 0; i < total_threads_to_create; i++) {
// create threads
pthread_create(&threads[i], NULL, handler_func, NULL);
}
for(int i=0;i<total_requests_to_make;i++){
// fill up the task queue
add_task_to_my_queue(i + 100);
}
for(int i = 0; i< total_threads_to_create; i++) {
// wait for threads to finish
pthread_join(threads[i], NULL);
}