[問題] semaphore使用的問題
開發平台(Platform): (Ex: Win10, Linux, ...)
Linux
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
GCC
問題(Question):
小弟是使用thread的新手,想練習一下semaphore的使用
下面連結的程式碼
開兩個thread,分別跑producer和consumer兩支function
Buffer是一個stack架構
producer: 將Buffer的top位置填值,並將stack的top位置往上加
consumer: 將Buffer的top位置填值為0,並將stack的top位置往下減
producer第一次填值為1,每次填值都會是上一次的值+1,直到值加到10000,
兩個thread就呼叫 pthread_exit(NULL); 離開,然後程式結束。
因為Buffer的空間有1000格,使用兩個semaphore變數: empty與full
producer進入,會將empty-1、full+1,就是放一個東西進Buffer的意思
consumer進入,會將empty+1、full-1,就是從Buffer拿走一個東西的意思
想請問一下
1.Buffer有1000格,一開始都沒有放東西,所以對empty與full init的方法是對的嗎?
sem_init(&empty, 0, 1000);
sem_init(&full, 0, 0);
2.我也好奇,sem_wait 和 sem_post 要怎麼知道Buffer有1000格呢?
要如何讓程式知道empty=1000表示Buffer是全空,full=1000表示Buffer是全滿呢?
3.另外小弟的code邏輯上是否有什麼錯誤嗎?
謝謝
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
https://ideone.com/MyhKC7 (new)
https://ideone.com/xv22NM (old)
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.192.95.44
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1526558837.A.907.html
※ 編輯: Zoxge (123.192.95.44), 05/17/2018 20:09:30
→
05/17 23:50,
7年前
, 1F
05/17 23:50, 1F
→
05/18 00:59,
7年前
, 2F
05/18 00:59, 2F
→
05/18 08:06,
7年前
, 3F
05/18 08:06, 3F
→
05/18 08:07,
7年前
, 4F
05/18 08:07, 4F
→
05/18 08:07,
7年前
, 5F
05/18 08:07, 5F
推
05/18 13:48,
7年前
, 6F
05/18 13:48, 6F
→
05/18 13:48,
7年前
, 7F
05/18 13:48, 7F
→
05/18 13:55,
7年前
, 8F
05/18 13:55, 8F
→
05/18 13:55,
7年前
, 9F
05/18 13:55, 9F
※ 編輯: Zoxge (123.192.95.44), 05/18/2018 22:35:25
→
05/18 22:36,
7年前
, 10F
05/18 22:36, 10F
→
05/18 22:37,
7年前
, 11F
05/18 22:37, 11F
→
05/18 22:38,
7年前
, 12F
05/18 22:38, 12F
→
05/18 22:38,
7年前
, 13F
05/18 22:38, 13F
→
05/18 22:39,
7年前
, 14F
05/18 22:39, 14F
※ 編輯: Zoxge (123.192.95.44), 05/18/2018 22:43:08
→
05/18 22:43,
7年前
, 15F
05/18 22:43, 15F
→
05/18 22:44,
7年前
, 16F
05/18 22:44, 16F
→
05/18 22:44,
7年前
, 17F
05/18 22:44, 17F
→
05/19 12:16,
7年前
, 18F
05/19 12:16, 18F
→
05/19 12:19,
7年前
, 19F
05/19 12:19, 19F
→
05/19 12:19,
7年前
, 20F
05/19 12:19, 20F
→
05/19 12:19,
7年前
, 21F
05/19 12:19, 21F
→
05/19 12:19,
7年前
, 22F
05/19 12:19, 22F