#include <pthread.h>
#include <stdio.h>
#include <unistd.h>pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;void* thread_function(void* arg) {printf("線程等待喚醒,鎖定互斥量...\n");pthread_mutex_lock(&mutex);printf("線程等待在條件變量上...,這個時候會阻塞這里,且釋放鎖\n");pthread_cond_wait(&cond, &mutex); // 線程被喚醒后繼續執行printf("線程被喚醒!\n");pthread_mutex_unlock(&mutex);return NULL;
}int main() {pthread_t thread_id;// 創建線程pthread_create(&thread_id, NULL, &thread_function, NULL);// 睡眠一段時間,以便讓線程先運行并等待條件變量sleep(5);// 喚醒等待在條件變量上的線程printf("主線程發送喚醒信號...\n");pthread_mutex_lock(&mutex);printf("主線程發送喚醒信號2...\n");pthread_cond_signal(&cond);printf("主線程發送喚醒信號3...\n");pthread_mutex_unlock(&mutex); //上面加鎖,這里就必須配套解鎖,否則即便pthread_cond_wait取不到鎖還是卡在那printf("主線程發送喚醒信號4...\n"); // 等待子線程結束printf("等待子線程結束 1...\n");pthread_join(thread_id, NULL);printf("等待子線程結束 2...\n");return 0;
}
makefile執行 :gcc ?optThread.c -lpthread -o ?opt ?
執行結果
?
fr:徐海濤(hunkxu)