当前位置: 技术问答>linux和unix
pthread_cond_timedwait用来让线程睡眠无效?
来源: 互联网 发布时间:2016-11-06
本文导语: nline static void thread_sleep(long int sec, long int milsec) { pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; struct timespec time; bzero(&time, sizeof(...
nline static void
thread_sleep(long int sec, long int milsec)
{
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct timespec time;
bzero(&time, sizeof(struct timespec));
time.tv_sec = sec;
time.tv_nsec = milsec * 1000000;
pthread_mutex_lock(&mutex);
pthread_cond_timedwait(&cond, &mutex, &time);
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
这么一个函数,发现根本无法让线程阻塞,直接就过去了
thread_sleep(long int sec, long int milsec)
{
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct timespec time;
bzero(&time, sizeof(struct timespec));
time.tv_sec = sec;
time.tv_nsec = milsec * 1000000;
pthread_mutex_lock(&mutex);
pthread_cond_timedwait(&cond, &mutex, &time);
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
这么一个函数,发现根本无法让线程阻塞,直接就过去了
|
pthread_cond_timedwait的时间参数是绝对时间,不是相对时间,你要用gettimeofday拿到现在的时间再加上interval