[英]How do I stop threads stalling on pthread_join?
我有一個項目,其中將作業添加到隊列中,並且有多個線程接收作業,並計算自己的獨立結果。
我的程序處理SIGINT信號,我試圖加入線程以將結果加起來,打印到屏幕上,然后退出。 我的問題是,當我發送信號時,線程似乎停止運行,或者在互斥鎖上被阻塞。 為了簡潔起見,這是我程序的重要部分。
main.c
//the thread pool has a queue of jobs inside
//called jobs (which is a struct)
struct thread_pool * pool;
void signal_handler(int signo) {
pool->jobs->running = 0; //stop the thread pool
pthread_cond_broadcast(pool->jobs->cond);
for (i = 0; i < tpool->thread_count; i++) {
pthread_join(tpool->threads[i], retval);
//do stuff with retval
}
//print results then exit
exit(EXIT_SUCCESS);
}
int main() {
signal(SIGINT, signal_handler);
//set up threadpool and jobpool
//start threads (they all run the workerThread function)
while (1) {
//send jobs to the job pool
}
return 0;
}
thread_stuff.c
void add_job(struct jobs * j) {
if (j->running) {
pthread_mutex_lock(j->mutex);
//add job to queue and update count and empty
pthread_cond_signal(j->cond);
pthread_mutex_unlock(j->mutex);
}
}
struct job * get_job(struct jobs * j) {
pthread_mutex_lock(j->mutex);
while (j->running && j->empty)
pthread_cond_wait(j->cond, j->mutex);
if (!j->running || j->empty) return NULL;
//get the next job from the queue
//unlock mutex and send a signal to other threads
//waiting on the condition
pthread_cond_signal(j->cond);
pthread_mutex_unlock(j->mutex);
//return new job
}
void * workerThread(void * arg) {
struct jobs * j = (struct jobs *) arg;
int results = 0;
while (j->running) {
//get next job and process results
}
return results;
}
感謝您的幫助,這真讓我頭疼!
您不應從處理異步生成的信號(例如SIGINT
的信號處理程序中調用pthread_cond_wait
或pthread_join
。 相反,您應該為所有線程阻止SIGINT
,產生一個專用線程,然后在那里調用sigwait
。 這意味着您可以在信號處理程序上下文之外檢測到SIGINT
信號的到達,因此您不僅可以使用異步信號安全函數 。 如果信號傳遞到工作線程之一,您還可以避免自鎖的風險。
此時,您只需要有序地關閉工作隊列/線程池。 根據細節的不同,您現有的帶有running
標志的方法甚至可能不會改變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.