互斥量mutex的簡(jiǎn)單使用(實(shí)例講解)
幾個(gè)重要的函數(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是動(dòng)態(tài)分配的,則釋放內(nèi)存前調(diào)用此函數(shù)。
int pthread_mutex_lock(pthread_mutex_t *mutex); //加鎖
int pthread_mutex_trylock(pthread_mutex_t *mutex); //若已有其他線(xiàn)程占用鎖,則返回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輸出會(huì)是50和200
b += 50; //加鎖后會(huì)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) //輪詢(xún)直到獲得鎖
{
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# 通過(guò)同步和異步實(shí)現(xiàn)優(yōu)化做早餐的時(shí)間
本文以一個(gè)簡(jiǎn)單的小例子—如何做一頓早餐及如何優(yōu)化做早餐的時(shí)間來(lái)讓大家具體了解一下同步和異步方法的區(qū)別,需要的朋友可以參考一下2021-12-12
C#使用DateAndTime.DateDiff實(shí)現(xiàn)計(jì)算年齡
這篇文章主要為大家詳細(xì)介紹了C#如何使用DateAndTime.DateDiff實(shí)現(xiàn)根據(jù)生日計(jì)算年齡,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2024-01-01
C#實(shí)現(xiàn)掃描槍掃描二維碼并打印(實(shí)例代碼)
這篇文章主要介紹了C#實(shí)現(xiàn)掃描槍掃描二維碼并打印,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01
c#語(yǔ)言使用Unity粒子系統(tǒng)制作手雷爆炸
這篇文章主要為大家介紹了Unity的粒子系統(tǒng)由粒子發(fā)射器、粒子動(dòng)畫(huà)器、粒子渲染器組成,通過(guò)使用一或兩個(gè)紋理多次繪制,創(chuàng)造一個(gè)混沌的效果,通過(guò)復(fù)習(xí)粒子系統(tǒng)做一個(gè)手雷和實(shí)彈投擲現(xiàn)場(chǎng)2022-04-04
C#基于正則表達(dá)式刪除字符串中數(shù)字或非數(shù)字的方法
這篇文章主要介紹了C#基于正則表達(dá)式刪除字符串中數(shù)字或非數(shù)字的方法,涉及C#針對(duì)數(shù)字的簡(jiǎn)單正則匹配相關(guān)操作技巧,需要的朋友可以參考下2017-06-06
C#連接db2數(shù)據(jù)庫(kù)的實(shí)現(xiàn)方法
本篇文章是對(duì)C#連接db2數(shù)據(jù)庫(kù)的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
本文主要介紹了C#中利用GDI來(lái)繪制圖形和文字的方法,并提供的簡(jiǎn)單的示例供大家參考學(xué)習(xí),希望能夠?qū)Υ蠹矣兴鶐椭?/div> 2016-03-03
C# 中的動(dòng)態(tài)創(chuàng)建組件(屬性及事件)的實(shí)現(xiàn)思路及方法
這篇文章主要介紹了C# 中的動(dòng)態(tài)創(chuàng)建組件,有需要的朋友可以參考一下2013-12-12最新評(píng)論

