common_thread_mutex thread_mutex;
typedef void* (*COMMON_THREAD_FUNCTION)(void*);
COMMON_THREAD_FUNCTION threadFunc;
Void *arg;
common_thread thread;
pthread_cond_t cond;
//设置线程的取消命令的状态,即:是否忽略这个请求。
// PTHREAD_CANCEL_ENABLE(缺省),即允许取消,要么是PTHREAD_CANCEL_DISABLE,即//不允许取消(收到的取消请求将被忽略)。
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
//设置线程的取消命令类型:PTHREAD_CANCEL_DEFERRED延迟执行,等到下一个取消点再、、//执行PTHREAD_CANCEL_ASYNCHRONOUS立即执行
//多线程中含有取消点作用的函数有
//pthread_join()
//pthread_cond_wait()
//pthread_cond_timedwait()
//pthread_testcancel()
//sem_wait()
//sigwait()
pthread_testcancel();//用于检测取消
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
pthread_mutex_init(&mutex, NULL); //创建线程锁
pthread_mutex_ lock (&mutex); //锁
if (pthread_create(&thread, NULL, threadFunc, arg) != 0)//创建线程
{
}
pthread_cond_wait(&cond, & mutex);//根据cond阻塞
struct timespec ts;
struct timeval tv;
gettimeofday(&tv, NULL);
ts.tv_sec = tv.tv_sec + INIT_WAIT_TIME;
ts.tv_nsec = tv.tv_usec * NANO_PER_MICRO;
rv = pthread_cond_timedwait(&timerq.cond, &timerq.mutex, &ts);
//设置线程锁的超市时间,线程锁会在设置的时间后 解锁
if (rv != 0) {
if (rv == ETIMEDOUT) {
pthread_cancel(timerq.ticker);
pthread_join(timerq.ticker, NULL);
}
pthread_mutex_destroy(&timerq.mutex);
pthread_cond_destroy(&timerq.cond);
return 0;
}
pthread_mutex_unlock(&mutex); //解锁
pthread_detach((uint32_t)common_thread_self());//设置unjoinable状态,线程退出时自动回收资源,避免内存泄漏
pthread_exit((void *)0);//线程退出
pthread_cancel(&thread);向其它线程发送取消命令
pthread_cond_signal(&cond);//发送一个信号给其它调用cond的阻塞线程,使其脱离阻塞状态