Pthread多线程超时取消

pthread线程库是posix标准,在应用多线程时候难免会遇到线程卡死在慢速IO上面的情况,这种情况应该对线程采用超时机制,即如果超时杀死线程。

 

杀死线程有两种方式一种是通过pthread_cancel()一种是通过pthread_kill发送信号捕捉信号的方式。

 

pthread_cancel的使用一直有很多争议,很多人不推荐使用它,在一些linuxBUGReprot上也总是看见它的影子,根据我的使用经验确实觉得这个函数实现的有些不完善。所以这里我给出一个用pthread_kill()发送信号,捕捉信号后线程自己退出的情况。使用时候注意退出时释放掉线程资源。

 

#include <iostream> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <signal.h> #include <string.h> #include <errno.h> #include <time.h> pthread_mutex_t mutex_timeout; pthread_cond_t cond_timeout; void alrm_signal(int); void* thread_work(void*); int main() { pthread_mutex_init(&mutex_timeout, NULL); pthread_cond_init(&cond_timeout, NULL); pthread_t thread; int rc; struct sigaction action; memset(&action, 0, sizeof(action)); sigemptyset(&action.sa_mask); action.sa_flags = 0; action.sa_handler = alrm_signal; rc = sigaction(SIGALRM, &action, NULL); if(rc) { printf("sigaction error/n"); exit(1); } struct timespec m_time; //等待30秒 m_time.tv_sec = time(NULL) + 30; m_time.tv_nsec = 0; rc = pthread_create(&thread, NULL, thread_work, NULL); if(rc) { printf("Create thread error /n"); exit(1); } pthread_mutex_lock(&mutex_timeout); int res = pthread_cond_timedwait(&cond_timeout, &mutex_timeout, (const struct timespec *)&m_time); pthread_mutex_unlock(&mutex_timeout); if(res == ETIMEDOUT)//timeout { printf("thread time out!/n"); pthread_kill(thread, SIGALRM); printf("sigalrm sent/n"); } else{ printf("back in time/n"); } printf("Main compelet!/n"); return 0; } void alrm_signal(int signo) { if(signo != SIGALRM) { printf("unexpect signal %d/n", signo); exit(1); } printf("/nSIGALRM has come. alrm_signal will kill timeout thread"); pthread_exit(0); return; } void* thread_work(void * param) { while(1) { printf("thread is sleeping .../n"); //如果不希望超时,可以通过修改sleep时间让pthread_cond_signal有机会唤醒主线程 sleep(100); printf("thread wake up/n"); pthread_mutex_lock(&mutex_timeout); pthread_cond_signal(&cond_timeout); pthread_mutex_unlock(&mutex_timeout); } return NULL; }

你可能感兴趣的:(thread,多线程,kill,null,action,Signal)