C 多執行緒 Mutex

2021-09-30 07:53:03 字數 3057 閱讀 7868

dotnet

2010-05-29 19:07:24

閱讀151

字型大小:大

小訂閱

互斥鎖(mutex)

互斥鎖是乙個互斥的同步物件,意味著同一時間有且僅有乙個執行緒可以獲取它。

互斥鎖可適用於乙個共享資源每次只能被乙個執行緒訪問的情況

函式://建立乙個處於未獲取狀態的互斥鎖

public mutex();

//如果owned為true,互斥鎖的初始狀態就是被主線程所獲取,否則處於未獲取狀態

public mutex(bool owned);

如果要獲取乙個互斥鎖。應呼叫互斥鎖上的waitone()方法,該方法繼承於thread.waithandle類

它處於等到狀態直至所呼叫互斥鎖可以被獲取,因此該方法將組織住主調執行緒直到指定的互斥鎖可用,如果不需要擁有互斥鎖,用releasemutex方法釋放,從而使互斥鎖可以被另外乙個執行緒所獲取。

code

using

system;

using

system.collections.generic;

using

system.linq;

using

system.text;

using

system.threading;

namespace

myttcon

class

incthread

void

run()

while

(number 

>0);

console.writeline(thrd.name +"

釋放 the nmutex");

//釋放

shareres.mutex.releasemutex();}}

class

decthread

void

run()

while

(number 

>0);

console.writeline(thrd.name +"

釋放 the nmutex");

//釋放

shareres.mutex.releasemutex();}}

class

program}}

system.threading.mutex在概念上和system.threading.monitor幾乎完全一致,只是lock關鍵字用的不是它,而且它旨在程序間的同步。

using

system;

using

system.collections.generic;

using

system.linq;

using

system.text;

using

system.threading;

namespace

class

test

else

console.readline();}}

}執行以上**生成的應用程式第乙個例項,會得到結果

running

保持第乙個執行狀態,執行第二個例項,得到結果

another 

isrunning

以上**中建立了乙個mutex,從其引數的解釋中得知,第乙個呼叫執行緒將得到互斥體的初始所屬權,如果不釋放的話,其他的執行緒得不到互斥體所有權

下面看一段**(出自 ),稍有改動

using

system;

using

system.collections.generic;

using

system.text;

using

system.threading;

namespace

monitorlockmutex

public

program()

public

void

runthread()

private

void

thread1func()

}private

void

thread2func() }

private

void

testfunc(

string

str) "

, str, system.datetime.now.millisecond);}}

}兩個執行緒基本上是按照各自的時間間隔+testfunc的執行時間對testfunc函式進行讀取

將公共呼叫的函式加鎖

private

void

testfunc(

string

str) "

, str, system.datetime.now.millisecond);

}            

}再次執行檢視結果,好像沒什麼區別?

加入mutex

private

void

thread1func()

mutex.releasemutex();

}private

void

thread2func()

mutex.releasemutex();

}再次執行檢視結果。

想到了什麼?thread1func() 或者thread2func()中的全部執行完畢,之後釋放互斥體,然後剩下的那個才可以訪問。

再改動一次

private

void

thread1func()

}           

}private

void

thread2func()

}           

}看效果……

輪換執行……

C 多執行緒同步 二 Mutex

monitor和lock多用於鎖定被呼叫端,而mutex則多用鎖定呼叫端。lock this 或者是用monitor也是一樣的,如下 monitor.enter this do something monitor.exit this monitor的好處是可以用tryenter this,timeo...

C 多執行緒 mutex類 (三)

mutex 類 詳細方法介紹參見c ref recursive mutex timed mutex recursive timed mutex 整合了recursive mutex和timed mutex特性 lock方法執行區別 對任意的mutex type物件,若其 cur mutex 已被其他...

C 多執行緒程式設計之mutex

參考 www.cplusplus.com 互斥量 互斥鎖,用於鎖住臨界區,防止多個執行緒同時處於臨界區中對臨界資源進行操作。c 中的 mutex是乙個類,可建立可鎖物件。mutex物件提供專屬所有權,且不支援遞迴。所謂專屬所有權是指,對已經被其他執行緒占有的mutex物件,當前執行緒不能再進行鎖操作...