📄 thrstartstop.c
字号:
/*------------------------------------------------------------------------- * thrstartstop.c - startthread, stopthread *------------------------------------------------------------------------- */#include <pthread.h>#include <signal.h>#include <util.h>#include <time.h>#include <errno.h>/*------------------------------------------------------------------------ * startthread - cleanly start a thread *------------------------------------------------------------------------ */intstartthread(pthread_t *thread, void *(*fcn)(void *), void *arg, pthread_mutex_t *mutex, pthread_cond_t *cond, int *statusvar){ int rv; pthread_mutex_lock(mutex); if (*statusvar == THR_RUNNING || *statusvar == THR_INITIALIZING) { pthread_mutex_unlock(mutex); return OK; } if (*statusvar == THR_TERMINATE) { pthread_mutex_unlock(mutex); return ERROR; } *statusvar = THR_INITIALIZING; rv = pthread_create(thread, NULL, fcn, (void *) arg); if (rv != 0) { *statusvar = THR_NOTRUNNING; pthread_mutex_unlock(mutex); return ERROR; } pthread_mutex_unlock(mutex); return OK;}/*------------------------------------------------------------------------ * stopthread - cleanly stop a thread; block until thread acknowledges *------------------------------------------------------------------------ */intstopthread(pthread_t *thread, pthread_mutex_t *mutex, pthread_cond_t *cond, int *statusvar){ int tries = 0; int rv; struct timespec time, delta = UTIL_STOPTHREADDELTA; pthread_mutex_lock(mutex); /* * Don't send signal before handler installed. */ while(*statusvar == THR_INITIALIZING) pthread_cond_wait(cond, mutex); if (*statusvar != THR_RUNNING) { pthread_mutex_unlock(mutex); return OK; } *statusvar = THR_TERMINATE; /* * Try UTIL_STOPTHREADMAXTRIES sending the SIGTERM * signal and waiting for an acknowledgement * before returning an error. */ while(*statusvar != THR_NOTRUNNING) { if (tries++ == UTIL_STOPTHREADMAXTRIES) { *statusvar = THR_RUNNING; pthread_mutex_unlock(mutex); return ERROR; } clock_gettime(CLOCK_REALTIME, &time); time = timeadd(time, delta); pthread_kill(*thread, SIGTERM); rv = pthread_cond_timedwait(cond, mutex, &time); if (rv != 0 && rv != ETIMEDOUT) { *statusvar = THR_RUNNING; pthread_mutex_unlock(mutex); return ERROR; } } *thread = 0; pthread_mutex_unlock(mutex); return OK;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -