阻塞佇列實現

2022-07-30 11:12:08 字數 1759 閱讀 1305

0前言

1實現原始碼

1.1 鎖封裝

通過訊號量保證不同執行緒之間資料操作的一致性。

class

csemaphore

~csemaphore()

void

produce()

void

consume()

}

bool

try()

return

true

; }

bool trytime(int

micsec)

int ret = sem_timedwait(&m_sem,&ts);

if(ret < 0

)

return

false

;

return

true

; }

intgetcount()

private

: sem_t m_sem;

};

view code

1.2 寫資料(訊息)

bool put(const __t&value)

m_queue.push_back(value);

m_semaphore.produce();

return

true

; }

1.3 讀取資料(訊息)    

bool get(__t&value)

2例項2.1 原始碼

2.2 輸出 

thread id : 139737310840576 output is: 557

thread id : 139737310840576 output is: 558

thread id : 139737310840576 output is: 559

thread id : 139737310840576 output is: 560

thread id : 139737310840576 output is: 561

thread id : 139737310840576 output is: 562

thread id : 139737310840576 output is: 563

thread id : 139737310840576 output is: 564

thread id : 139737310840576 output is: 565

thread id : 139737300350720 output is: 566

thread id : 139737300350720 output is: 567

thread id : 139737300350720 output is: 568

thread id : 139737300350720 output is: 569

thread id : 139737300350720 output is: 570

thread id : 139737310840576 output is: 571

原始碼請見附件

基於陣列實現阻塞佇列

基於陣列實現的話,需要額外兩個指標,乙個指向頭元素,乙個指向尾元素。出的時候從頭元素出去,入的時候從尾元素入。即出的時候tail指標 1,入的時候尾指標 1 因此使用乙個環形佇列最好,不會浪費空間也不需要挪動元素位置。因為是環形佇列,因此tail在最後乙個位置的時候,再進來乙個元素,如果佇列不滿,就...

等待佇列 阻塞非阻塞

阻塞 裝置驅動不阻塞,使用者想獲取裝置資源只能不停的查詢,這無謂的消耗cpu資源。而阻塞訪問,不能獲取資源的程序將進入休眠,它將cpu資源 禮讓 給其他程序 喚醒程序的地方最大可能發生在中斷裡面,因為硬體資源獲得的同時往往伴隨著乙個中斷 定義頭 wait queue head t queue 初始化...

阻塞佇列BlockingQueue

例介紹乙個特殊的佇列 blockingqueue,如果blockingqueue是空的,從blockingqueue取東西的操作將會被阻斷進入等待狀態,直到blockingqueue進了東西才會被喚醒,同樣,如果blockingqueue是滿的,任何試圖往裡存東西的操作也會被阻斷進入等待狀態,直到b...