一、代碼如下
#include<stdio.h>
#include<pthread.h>
?
// 定義獨占鎖?
pthread_mutex_t mutex;?
// 定義條件信號對象
pthread_cond_t condition;
?// 初始化函數
void init(){
?? ?
?? ?int code = pthread_mutex_init(&mutex, NULL);
?? ?printf("共享鎖初始化狀態:%d \n", code);
?? ?
?? ?
?? ?code = pthread_cond_init(&condition, NULL);?
?? ?printf("共享條件變量初始化狀態:%d \n", code);
}?
// 線程的邏輯
void* run(void* arg){
? ? printf("進入休眠狀態.\n");?
? ? // 加鎖
? ? pthread_mutex_lock(&mutex);
? ??
?? ?// 休眠
?? ?pthread_cond_wait(&condition, &mutex);
?? ?
?? ?printf("被喚醒,退出。\n");??
? ? // 釋放鎖
?? ?pthread_mutex_unlock(&mutex);
}
// 測試線程休眠和喚醒?
int main(){
?? ?init();
?? ?
?? ?pthread_t pid;
??? ? // 創建一個線程運行?
?? ?pthread_create(&pid, NULL, run, NULL);?
?? ?? ? // 獲得排他鎖
?? ?pthread_mutex_lock(&mutex);
? ??
? ? printf("請輸入一個字母,喚醒線程:\n");
? ? getchar();
? ??
?? ?// 喚醒那些處在休眠的線程
?? ?pthread_cond_signal(&condition);
?? ? // 釋放排他鎖
?? ?pthread_mutex_unlock(&mutex);
?? ?
?? ?getchar();
?? ?// pthread_join(pid, NULL);
?? ?
?? ?return 0;
}
?
說明:
? ?1、線程只有獲得鎖才能休眠;
? ?2、線程休眠后排他鎖就釋放了;
? ?3、處在休眠的線程可以被其他線程獲得排他鎖后喚醒;
?