1. 程式人生 > >Linux多線程編程 - sleep 和 pthread_cond_timedwait

Linux多線程編程 - sleep 和 pthread_cond_timedwait

ext flag style lock table stdio.h 線程編程 include ble

#include <stdio.h> #include <stdlib.h>

int flag = 1; void * thr_fn(void * arg) { while (flag){ printf("******\n"); sleep(10); } printf("sleep test thread exit\n"); } int main() { pthread_t thread; if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) { printf("error when create pthread,%d\n", errno); return 1; } char c ; while ((c = getchar()) != ‘q‘); printf("Now terminate the thread!\n"); flag = 0; printf("Wait for thread to exit\n"); pthread_join(thread, NULL); printf("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> static pthread_t thread; static pthread_cond_t cond; static pthread_mutex_t mutex; static int flag = 1; void * thr_fn(void * arg) { struct timeval now; struct timespec outtime; pthread_mutex_lock(&mutex); while (flag) { printf("*****\n"); gettimeofday(&now, NULL); outtime.tv_sec = now.tv_sec + 5; outtime.tv_nsec = now.tv_usec * 1000; pthread_cond_timedwait(&cond, &mutex, &outtime); } pthread_mutex_unlock(&mutex); printf("cond thread exit\n"); } int main(void) { pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) { printf("error when create pthread,%d\n", errno); return 1; } char c ; while ((c = getchar()) != ‘q‘); printf("Now terminate the thread!\n");

pthread_mutex_lock(&mutex); flag = 0; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); printf("Wait for thread to exit\n"); pthread_join(thread, NULL); printf("Bye\n"); return 0; }

pthread_cond_timedwait()函數阻塞住調用該函數的線程,等待由cond指定的條件被觸發(pthread_cond_broadcast() or pthread_cond_signal())。

  當pthread_cond_timedwait()被調用時,調用線程必須已經鎖住了mutex。函數pthread_cond_timedwait()會對mutex進行【解鎖和執行對條件的等待】(原子操作)。

Linux多線程編程 - sleep 和 pthread_cond_timedwait