linux c 多執行緒互斥鎖

2021-10-19 12:13:23 字數 1030 閱讀 7318

beers.c

#include

#include

#include

#include

#include

#include

int beers =

2000000

;// 建立互斥鎖,互斥鎖對所有可能發生衝突的執行緒可見,是乙個全域性變數.

// pthread_mutex_initializer實際上是乙個巨集,當編譯器看到它,就會插入建立互斥鎖的**

pthread_mutex_t beers_lock = pthread_mutex_initializer;

void

*drink_lots_1

(void

* a)

// ...**結束了

pthread_mutex_unlock

(&beers_lock)

;printf

("beers = %i \n"

, beers)

;return

null;}

// 另外一種上鎖方式

void

*drink_lots

(void

* a)

printf

("beers = %i \n"

, beers)

;return

null;}

void

error

(char

*msg)

intmain()

void

* result;

for(t =

0; t <

20; t++

)printf

("there are now %i bottles of beer on the wall\n"

, beers)

;return0;

}

build:

gcc beers.c -lpthread -o beers

多執行緒 互斥鎖

include include include handle mutex null srwlock g lock 改變乙個變數的時候需要鎖定 int num 6400000 在讀期間,值一直在變化,沒有鎖定。dword winapi reada void p i 使用acquiresrwlocksh...

多執行緒 互斥鎖

package com.yys.thread created by yys on 2017 9 25.兩個執行緒執行 t1如果能拿到02物件則t1執行緒執行完畢 t2如果能拿到o1物件則t2執行緒執行完畢 現在兩個執行緒分別鎖定了對方需要的物件 造成執行緒死鎖 public class testde...

多執行緒 互斥鎖

使用reentrantlock類的lock和unlock方法進行同步通訊 使用reentrantlock類的newcondition方法可以獲取condition物件,需要等待的時候使用conditionde await方法,喚醒的時候用signal方法,不同的執行緒使用不同的condition,這...