대기열에 작업을 추가하는 프로젝트가 있고 여러 스레드에서 작업을 수행하고 자체 독립적 인 결과를 계산합니다.pthread_join에서 스레드가 멈추는 것을 어떻게 중지합니까?
내 프로그램이 SIGINT 신호를 처리하고 스레드를 결합하여 결과를 추가하고 화면에 인쇄 한 다음 종료합니다. 내 문제는 스레드가 신호를 보낼 때 스레드가 작동을 멈추는 것처럼 보이거나 mutex_lock에서 차단되고 있다는 것입니다. 여기 내 프로그램의 중요한 부분이 간결하게 소개되어 있습니다.
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;
}
도와
감사하는 것은, 이것은 나에게 진짜 두통을주고있다!
[이 POSIX 신호 개념 참조] (http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04)를 읽으면 2.4.3 절의 끝에 * async-safe * 기능을 가지고 있으므로 신호 처리기에서 안전하게 사용할 수 있습니다. 해당 목록을 살펴보면 ['pthread_join] (http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html)이 * 나열되지 * 않은 것으로 나타납니다. 즉 신호 처리기에서 호출해서는 안됩니다. –