一、函數約定
1、初始化鎖
int? ??pthread_mutex_init(pthread_mutex_t*? ?m, const pthread_mutexattr_t*? ?attr)
?
2、加鎖
int? ? pthread_mutex_lock(pthread_mutex_t*? ?m);
?
3、解鎖
int? ?pthread_mutex_unlock(pthread_mutex_t*? m);
?4、銷毀
int? ? ?pthread_mutex_destroy(pthread_mutex_t*? m);
?
?
二、代碼如下
#include<pthread.h>
#include<stdio.h>
// 定義結構體變量,代表一個互斥鎖?
pthread_mutex_t mutex;?
// 線程函數,描述線程的邏輯
void* thread_func(void* arg)
{
?? ?// 加鎖
? ? pthread_mutex_lock(&mutex);?
? ??
? ? int* total = (int*)arg;
? ??
? ? int k;
? ? for(k = 1; k <= 1000; k++){
? ? ?? ?*total = *total + 1;
?? ?}
?? ?
? ? // 執行一些需要互斥訪問的操作
? ? // 轉賬,修改共享數據?
? ??
? ? // update("id", "新值");
? ??
? ? // 解鎖
? ? pthread_mutex_unlock(&mutex);?
? ??
? ? printf("線程%d計算完畢\n", pthread_self());
? ? return NULL;
}
// pthread庫的加鎖和解鎖操作。?
int main()
{? ?// 共享數據
?? ?int total = 0;
?? ?
?? ?// 初始化互斥鎖
? ? pthread_mutex_init(&mutex, NULL);?
? ??
? ? pthread_t t1;
? ? pthread_t t2;
? ??
? ? // 創建和啟動線程
? ? // 同時建立兩個?
? ? pthread_create(&t1, NULL, thread_func, &total);
? ? pthread_create(&t2, NULL, thread_func, &total);
? ??
? ??
? ? // 等待子線程結束
?? ?pthread_join(t1, NULL);
?? ?pthread_join(t2, NULL);?
?? ?
?? ?printf("計算結果:%d \n", total);
? ??
? ? // 銷毀互斥鎖
? ? pthread_mutex_destroy(&mutex);
? ??
? ? return 0;
}
?
?