【发布时间】:2011-03-23 14:20:00
【问题描述】:
我在使用 pthread 时遇到了一点问题。基本上,我想捕获一个 SIGINT 并清理所有线程并退出。我有什么(骨架代码):
main.c:
sig_atomic_t running;
void handler(int signal_number)
{
running = 0;
}
int main(void)
{
queue job_queue = new_job_queue();
running = 1;
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &handler;
sigaction(SIGINT, &sa, NULL);
/* create a bunch of threads */
init_threads(&job_queue);
while(running) {
/* do stuff */
}
cleanup();
return (0);
}
threads.c
extern sig_atomic_t running;
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t queue_count;
void init_threads(queue *q)
{
int numthreads = 12; /* say */
sem_init (&queue_count, 0, 0);
pthread_t worker_threads[numthreads];
int i;
for(i=0;i<numthreads;i++)
pthread_create(&worker_threads[i], NULL, &thread_function, q);
}
void * thread_function(void *args)
{
pthread_detatch(pthread_self());
queue *q = (queue *)args;
while(running) {
job *j = NULL;
sem_wait(&queue_count);
pthread_mutex_lock(&queue_mutex);
j = first_job_in_queue(q);
pthread_mutex_unlock(&queue_mutex);
if(j) {
/*do something*/
}
}
return (NULL);
}
我在这方面运气不佳。由于您不能保证哪个线程会收到信号,所以我认为这是一个好方法。但是我遇到了一个问题,thread.c 中的sem_wait() 挂起,这是预期但不希望的。 threads.c 中的while(running) 循环似乎是多余的。我应该对 main 中的所有线程执行pthread_kill() 吗?上面的骨架代码有什么明显的问题吗?有没有更好/更简单的方法来做到这一点?
谢谢。
【问题讨论】: