1.編寫所需標頭檔案
#include
#include
2.定義全域性變數
#define productor 2
//生產者數目 為2
#define consumers 3
//消費者數目 為3
#define buffers 10
//緩衝區數目 為10
int nextp1 =
1000
;//生產者1生產資料
int nextp2=
2000
;//生產者2生產資料
int buf[buffers]=;
//緩衝區陣列
file *fpwrite=
fopen
("d:\\4.txt"
,"w");
//日誌檔案寫入位置
3.編寫相關訊號量
empty =
createsemaphore
(null
, buffers, buffers,
null);
//訊號量,緩衝區空位數量
full =
createsemaphore
(null,0
, buffers,
null);
//訊號量,緩衝區資料的個數
huchu =
createsemaphore
(null,1
,1,null);
//訊號量,緩衝區互斥使用
第二個引數為初始量,第三個引數為最大值
4.編寫建立執行緒函式
hthread[i]
=createthread
(null,0
, producer,
(lpvoid*
)&pid[i],0
,null);
//建立生產者執行緒
hthread[i + productor]
=createthread
(null,0
, consumer,
(lpvoid*
)&cid[i],0
,null);
//建立消費者程序
p
(empty);p
(huchu);if
(id==1)
else
//通過id判斷是哪乙個生產者,生產不同資料
v(huchu);v
(full)
;
消費者關鍵**:
p
(full);p
(huchu)
;fprintf
(fpwrite,
"\t\t\t\t\t\t消費者%d 將資料%d 取出緩衝區%d\n"
, id, num, out)
;out =
(out +1)
% buffers;
v(huchu);v
(empty)
;
6.編寫執行緒關閉,io關閉
waitformultipleobjects
(num_of_thread, hthread, true, infinite)
;printf
("寫入完成\n"
);
#include
#include
#define productor 2
#define consumers 3
#define buffers 10
#define p(s) waitforsingleobject(s,infinite)
#define v(s) releasesemaphore(s,1,null)
int nextp1 =
1000
;int nextp2=
2000
;int in =
0, out =0;
int buf[buffers]=;
file *fpwrite=
fopen
("d:\\4.txt"
,"w"
);
handle empty, full;
handle huchu;
dword winapi producer
(lpvoid pm)
else
in =
(in +1)
% buffers;
v(huchu);v
(full);if
(nextp1 >
1200
||nextp2>
2200)}
return0;
}dword winapi consumer
(lpvoid pm)
}return0;
}int
main()
int cid[2]
;for
(int i =
0; i < consumers; i++
)waitformultipleobjects
(num_of_thread, hthread, true, infinite)
;printf
("寫入完成\n");
生產者消費者問題C語言
include include include include include include include define n 4 int buf n int putin 0 int takeout 0 時延函式 void delay int len i 生產者 void producer 消費者...
生產者消費者問題
public class producer consumer class godown public godown int num public synchronized void produce int n catch interruptedexception e curr num n syste...
生產者 消費者問題
在學習程序互斥中,有個著名的問題 生產者 消費者問題。這個問題是乙個標準的 著名的同時性程式設計問題的集合 乙個有限緩衝區和兩類執行緒,它們是生產者和消費者,生產者把產品放入緩衝區,相反消費者便是從緩衝區中拿走產品。生產者在緩衝區滿時必須等待,直到緩衝區有空間才繼續生產。消費者在緩衝區空時必 須等待...