乙個寫優先的讀寫鎖實現

2021-06-20 14:53:55 字數 2668 閱讀 5192

/* g++ -wall -o rwlock rwlock.cpp -lpthread

** 乙個寫優先讀寫鎖的實現,多執行緒頻繁讀,多執行緒少量寫,同時寫優先,效能極佳。

* 當寫鎖(獨佔鎖)lock成功的必要條件是:

* 1. 將寫鎖計數++;

* 2. 會阻塞後續對讀鎖(共享鎖)的讀;

* 3. 等待讀鎖的計數為0;

* 4. 等待寫鎖的計數為1;**/

#include

#include

#include

#include

#include

using

namespace

std;

class

rwlock

void

get_shared_lock

()pthread_mutex_unlock

(&cnt_mutex);}

void

release_shared_lock

()pthread_mutex_unlock

(&cnt_mutex);}

void

get_exclusive_lock

()printf

("*****\t\t w_lock[thread_0x%x] get ok r=%d w=%d\n",(

int)

tag,

rd_cnt

,wr_cnt

);pthread_mutex_unlock

(&cnt_mutex);}

void

release_exclusive_lock()~

rwlock

()};

static

rwlock

lock

;class

test

return

null;}

static

void

*exclusive_task_handler

(void

*)return

null;}

public

:typedef

void*(*

threadfunc)(

void

*);void

start()}

i =100;

ret

=pthread_create

(threads+i

,null

,exclusive_task_handler

,null

);if

(ret !=0

)}};int

main()}

執行結果:

[1257927661

]r_lock

[thread_0xb7c9fba0]r

=1w=

0[1257927661

]r_lock

[thread_0xb749eba0]r

=2w=

0[1257927662

]r_unlock

[thread_0xb7c9fba0]r

=1w=

0[1257927662

]r_unlock

[thread_0xb749eba0]r

=0w=

0r_unlock

[thread_0xb749eba0

]rd_cnt=0

,so singal to wr_cnt[0

]*****[

1257927663

]w_lock

[thread_0xb6c9dba0]r

=0w=

1*****

w_lock

[thread_0xb6c9dba0

]get

ok r=0

w=1[

1257927663

]r_lock

[thread_0xb749eba0]r

=1w=

1r_lock wait

forwr_cnt[1

][1257927663

]r_lock

[thread_0xb7c9fba0]r

=2w=

1r_lock wait

forwr_cnt[1

]*****[

1257927664

]w_unlock

[thread_0xb6c9dba0]r

=2w=

0,then

broadcast

[1257927665

]r_unlock

[thread_0xb749eba0]r

=1w=

0[1257927665

]r_unlock

[thread_0xb7c9fba0]r

=0w=

0r_unlock

[thread_0xb7c9fba0

]rd_cnt=0

,so singal to wr_cnt[0

][1257927666

]r_lock

[thread_0xb749eba0]r

=1w=

0[1257927666

]r_lock

[thread_0xb7c9fba0]r

=2w=

0

c 11實現寫優先的讀寫鎖

文章 先直接貼出 ifndef write first rw lock h define write first rw lock h include include class wfirstrwlock read cnt void lock write inwriteflag true void r...

設計乙個讀寫鎖

關係讀寫 讀yn寫 nn除了可以同時進行讀操作,其他操作均不允許。我得知道多少個執行緒在讀,多少個執行緒在寫,這樣在加讀鎖或者寫鎖的時候便可以控制其他執行緒是執行,還是等待。public class readwritelock catch interruptedexception e this re...

C 讀寫鎖 實現優先寫

讀寫互斥量 當有寫和讀操作同時競爭時,寫操作優先與讀操作 class crwmutex virtual crwmutex default void lockread 沒有寫等待時,可執行讀 m read count void unlockread void lockwrite 沒有讀操作並且沒有正在...