互斥量mutex的簡單使用(實例講解)
幾個重要的函數(shù):
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutex_t *restrict attr); //初始化mutex
int pthread_mutex_destroy(pthread_mutex_t *mutex); //如果mutex是動態(tài)分配的,則釋放內(nèi)存前調(diào)用此函數(shù)。
int pthread_mutex_lock(pthread_mutex_t *mutex); //加鎖
int pthread_mutex_trylock(pthread_mutex_t *mutex); //若已有其他線程占用鎖,則返回EBUSY,否則返回0,不阻塞。
int pthread_mutex_unlock(pthread_mutex_t *mutex); //解鎖
例程:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
int a = 100;
int b = 200;
pthread_mutex_t lock;
void * threadA()
{
pthread_mutex_lock(&lock);
printf("thread A got lock!\n");
a -= 50;
sleep(3); //如果不加鎖,threadB輸出會是50和200
b += 50; //加鎖后會sleep 3秒后,并為b加上50 threadB才能打印
pthread_mutex_unlock(&lock);
printf("thread A released the lock!\n");
a -= 50;
}
void * threadC()
{
sleep(1);
while(pthread_mutex_trylock(&lock) == EBUSY) //輪詢直到獲得鎖
{
printf("thread C is trying to get lock!\n");
usleep(100000);
}
printf("thread C got the lock!\n");
a = 1000;
b = 2000;
pthread_mutex_unlock(&lock);
printf("thread C released the lock!\n");
}
void * threadB()
{
sleep(2); //讓threadA能先執(zhí)行
pthread_mutex_lock(&lock);
printf("thread B got the lock! a=%d b=%d\n", a, b);
pthread_mutex_unlock(&lock);
printf("thread B released the lock!\n", a, b);
}
int main()
{
pthread_t tida, tidb, tidc;
pthread_mutex_init(&lock, NULL);
pthread_create(&tida, NULL, threadA, NULL);
pthread_create(&tidb, NULL, threadB, NULL);
pthread_create(&tidc, NULL, threadC, NULL);
pthread_join(tida, NULL);
pthread_join(tidb, NULL);
pthread_join(tidc, NULL);
return 0;
}
相關(guān)文章
C#實現(xiàn)按數(shù)據(jù)庫郵件列表發(fā)送郵件的方法
這篇文章主要介紹了C#實現(xiàn)按數(shù)據(jù)庫郵件列表發(fā)送郵件的方法,涉及C#讀取數(shù)據(jù)庫及通過自定義函數(shù)發(fā)送郵件的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07C#面向?qū)ο缶幊讨氯螒驅(qū)崿F(xiàn)方法
這篇文章主要介紹了C#面向?qū)ο缶幊讨氯螒驅(qū)崿F(xiàn)方法,以一個完整的猜拳游戲為例講述了C#面向?qū)ο蟪绦蛟O(shè)計的具體實現(xiàn)步驟,具有一定的學(xué)習(xí)與借鑒價值,需要的朋友可以參考下2014-11-11C#的靜態(tài)工廠方法與構(gòu)造函數(shù)相比有哪些優(yōu)缺點
這篇文章主要介紹了C#的靜態(tài)工廠方法與構(gòu)造函數(shù)對比的優(yōu)缺點,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07C# IP地址與整數(shù)之間轉(zhuǎn)換的具體方法
這篇文章介紹了C# IP地址與整數(shù)之間轉(zhuǎn)換的具體方法,有需要的朋友可以參考一下2013-10-10C# DataSet的內(nèi)容寫成XML時如何格式化字段數(shù)據(jù)
許多讀者經(jīng)常詢問一個問題,那就是在將DataSet的內(nèi)容寫成XML時,如何格式化字段數(shù)據(jù)。最常見的需求,就是希望日期時間值與數(shù)值數(shù)據(jù)能夠以所需的格式呈現(xiàn)于XML中。2009-02-02