互斥體(Mutex)和條件變量(Condition Variable)
互斥體(Mutex)和條件變量(Condition Variable)都是C語(yǔ)言中多線程編程中常用的同步機(jī)制,它們的主要差異在于互斥體用于保護(hù)臨界區(qū)(Critical Section)中的共享數(shù)據(jù),而條件變量用于在線程之間進(jìn)行通信和同步。
互斥體是一種線程同步的機(jī)制,用于保護(hù)臨界區(qū)中的共享資源,避免多個(gè)線程同時(shí)對(duì)共享資源進(jìn)行讀寫(xiě),導(dǎo)致數(shù)據(jù)不一致或者競(jìng)態(tài)條件的問(wèn)題?;コ怏w通常是一個(gè)鎖,它可以保證同一時(shí)刻只有一個(gè)線程可以進(jìn)入臨界區(qū),其他線程必須等待當(dāng)前線程釋放鎖之后才能進(jìn)入。
下面是一個(gè)簡(jiǎn)單的使用互斥體實(shí)現(xiàn)線程同步的例子代碼:
#include <stdio.h>
#include <pthread.h>
// 定義全局變量和互斥體
int sum = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// 線程函數(shù),將1~100的整數(shù)相加
void* thread_func(void* arg) {
? ?int i;
? ?for (i = 1; i <= 100; i++) {
? ? ? ?// 加鎖
? ? ? ?pthread_mutex_lock(&mutex);
? ? ? ?sum += i;
? ? ? ?// 解鎖
? ? ? ?pthread_mutex_unlock(&mutex);
? ?}
? ?pthread_exit(NULL);
}
int main() {
? ?// 定義線程ID和屬性
? ?pthread_t thread;
? ?pthread_attr_t attr;
? ?pthread_attr_init(&attr);
? ?// 創(chuàng)建線程
? ?pthread_create(&thread, &attr, thread_func, NULL);
? ?// 主線程將1~100的整數(shù)相加
? ?int i;
? ?for (i = 1; i <= 100; i++) {
? ? ? ?// 加鎖
? ? ? ?pthread_mutex_lock(&mutex);
? ? ? ?sum += i;
? ? ? ?// 解鎖
? ? ? ?pthread_mutex_unlock(&mutex);
? ?}
? ?// 等待子線程結(jié)束
? ?pthread_join(thread, NULL);
? ?// 輸出結(jié)果
? ?printf("sum = %d\n", sum);
? ?return 0;
}
在上面的例子中,我們使用了pthread_mutex_lock和pthread_mutex_unlock函數(shù)來(lái)加鎖和解鎖互斥體,以保證線程之間的同步。
條件變量是一種線程間通信的機(jī)制,用于在線程之間傳遞信息和同步,它通常用于等待某個(gè)特定事件的發(fā)生,例如,等待一個(gè)資源變得可用或者等待一個(gè)條件滿足。條件變量需要和互斥體一起使用,以保證線程之間的同步和互斥。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int count = 0;
void* thread_func(void* arg) {
? ?// 加鎖
? ?pthread_mutex_lock(&mutex);
? ?// 等待條件變量
? ?while (count == 0) {
? ? ? ?pthread_cond_wait(&cond, &mutex);
? ?}
? ?// 執(zhí)行任務(wù)
? ?printf("thread_func: count = %d\n", count);
? ?// 解鎖
? ?pthread_mutex_unlock(&mutex);
? ?pthread_exit(NULL);
}
int main() {
? ?// 定義線程ID和屬性
? ?pthread_t thread;
? ?pthread_attr_t attr;
? ?pthread_attr_init(&attr);
? ?// 初始化互斥體和條件變量
? ?pthread_mutex_init(&mutex, NULL);
? ?pthread_cond_init(&cond, NULL);
? ?// 創(chuàng)建線程
? ?pthread_create(&thread, &attr, thread_func, NULL);
? ?// 主線程增加計(jì)數(shù)器
? ?pthread_mutex_lock(&mutex);
? ?count++;
? ?printf("main: count = %d\n", count);
? ?// 發(fā)送信號(hào)給條件變量
? ?pthread_cond_signal(&cond);
? ?// 解鎖
? ?pthread_mutex_unlock(&mutex);
? ?// 等待子線程結(jié)束
? ?pthread_join(thread, NULL);
? ?// 銷毀互斥體和條件變量
? ?pthread_mutex_destroy(&mutex);
? ?pthread_cond_destroy(&cond);
? ?return 0;
}
在上面的例子中,我們使用了pthread_cond_wait函數(shù)等待條件變量,當(dāng)計(jì)數(shù)器count被主線程增加到1時(shí),主線程發(fā)送信號(hào)給條件變量,使得等待該條件變量的子線程可以繼續(xù)執(zhí)行。同時(shí),我們使用了互斥體保護(hù)共享數(shù)據(jù)count,以避免競(jìng)態(tài)條件的出現(xiàn)。
總的來(lái)說(shuō),使用條件變量可以實(shí)現(xiàn)線程之間的同步和通信,通過(guò)pthread_cond_wait和pthread_cond_signal函數(shù)的配合使用,可以在線程之間傳遞信息,使得一個(gè)線程等待另一個(gè)線程滿足某個(gè)條件后再繼續(xù)執(zhí)行。