Linux多线程编程-sleep和pthread_cond_timedwait
#include <stdio.h>
#include <stdlib.h>
int flag = 1
void * thr_fn(void * arg) {
while (flag){
rintf("******\n")
leep(10)
}
rintf("sleep test thread exit\n")
}
int main() {
thread_t thread
if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) {
rintf("error when create pthread,%d\n", errno)
return 1
}
char c
while ((c = getchar()) != 'q')
rintf("Now terminate the thread!\n")
flag = 0
rintf("Wait for thread to exit\n")
thread_join(thread, NULL)
rintf("Bye\n")
return 0
}
输入q后,需要等线程从sleep中醒来(由挂起状态变为运行状态),即最坏情况要等10s,线程才会被join。采用sleep的缺点:不能及时唤醒线程。
采用pthread_cond_timedwait函数,条件到了,线程即会被join,可及时唤醒线程。实现的如下:
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
tatic pthread_t thread
tatic pthread_cond_t cond
tatic pthread_mutex_t mutex
tatic int flag = 1
void * thr_fn(void * arg)
{
truct timeval now
truct timespec outtime
thread_mutex_lock(&mutex)
while (flag) {
rintf("*****\n")
gettimeofday(&now, NULL)
outtime.tv_sec = now.tv_sec + 5
outtime.tv_nsec = now.tv_usec * 1000
thread_cond_timedwait(&cond, &mutex, &outtime)
}
thread_mutex_unlock(&mutex)
rintf("cond thread exit\n")
}
int main(void)
{
thread_mutex_init(&mutex, NULL)
thread_cond_init(&cond, NULL)
if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) {
rintf("error when create pthread,%d\n", errno)
return 1
}
char c
while ((c = getchar()) != 'q')
rintf("Now terminate the thread!\n")
thread_mutex_lock(&mutex)
flag = 0
thread_cond_signal(&cond)
thread_mutex_unlock(&mutex)
rintf("Wait for thread to exit\n")
thread_join(thread, NULL)
rintf("Bye\n")
return 0
}
thread_cond_timedwait()函数阻塞住调用该函数的线程,等待由cond指定的条件被触发(pthread_cond_broadcast() or pthread_cond_signal())。
当pthread_cond_timedwait()被调用时,调用线程必须已经锁住了mutex。函数pthread_cond_timedwait()会对mutex进行【解锁和执行对条件的等待】(原子操作)。