您好,我正在做一個關於使用帶有多信號量的POSIX線程的任務。對任務的簡要說明是:有4個不同的數據包(char/video/audio/image),每個數據包由不同的線程攜帶,並且我們有一個共享緩衝區。用戶可以在系統上工作的最大線程數作爲輸入。例如;如果用戶輸入10,則可以創建最多10個線程,以在給定時間內通過緩衝區傳輸數據包。現在令我感到困惑的是,這個緩衝區可以立即包含有限的數據包。 (例如,它可以包含最多10個字符數據包和20個視頻數據包等),所以我們必須爲每種數據類型設置不同的信號量。我知道如何使用信號量來控制緩衝區大小,這很簡單,但不能設置使用信號量信息包的正確思想。即使我嘗試了一些不同的方法,我總是面臨死鎖錯誤。這裏是我的僞代碼,以更清楚地瞭解我的程序。關於使用多個信號量的同步
define struct packege
define semaphore list
main
initialize variables and semaphores
while threadCounter is less than MaxThreadNumber
switch(random)
case 0: create a character package
create a thread to insert the package in buffer
case 1: create a video package
create a thread to insert the package in buffer
case 2: create an image package
create a thread to insert the package in buffer
case 3: create an audio package
create a thread to insert the package in buffer
increment threadCounter by one
end of while
create only one thread which will make the dequeue operation
end of main
producer function
for i->0 to size_of_package
sem_wait(empty_buffer) // decrement empty_buffer semaphore by size of package
lock_mutex
insert item into queueu
decrement counter of the buffer by size of package
unlock_mutex
for i->0 to size_of_package
sem_post(full_buffer) // increment full_buffer semaphore by size of package
end of producer function
consumer function
while TRUE // Loops forever
lock_mutex
if queue is not empty
dequeue
increment counter of the buffer size of package
unlock_mutex
for i->0 to size_of_package // The reason why i making the sem_wait operation here is i cant make the dequeue in outer region of mutex.
sem_wait(full_buffer)
for i->0 to size_of_package
sem_post(empty_buffer)
end of consumer function
與此實現程序正常工作。但我不能正確使用屬於包的線程的信號量。我可以聽取每個建議,並會爲每個答案而感激。
在你的代碼中,消費者實際上並不知道它從緩衝區讀取什麼類型的數據。這個可以嗎? – didierc
我認爲你的意思是表明你想用一個信號量來配置總線程併發線程數,而N信號量多一個用於每個數據包*類型*來定量任何單個數據包類型的併發線程數。這甚至接近準確嗎?有點困惑.. – WhozCraig
@didierc yeap有沒有問題,我安排的參數,使其正常工作。首先,我將結構作爲參數發送給生產者,消費者在互斥體中進行出隊操作。隊列是全局定義的。 – quartaela