#include <windows.h> |
#include <stdio.h> |
#include <iostream> |
bool g_continue= true ; |
DWORD WINAPI Thread1( LPVOID lpPara); //线程1 |
DWORD WINAPI Thread2( LPVOID lpPara); //线程2 |
struct buffer |
{ |
int bufferpd; //存放产品 |
bool bufferzt; //状态 |
}; |
HANDLE hmutex=CreateMutex(NULL,FALSE, "readcoutmtx" ); |
HANDLE hfull=CreateSemaphore(NULL,0,10, "bufferfull" ); |
HANDLE hempty=CreateSemaphore(NULL,10,10, "butterhempty" ); |
int main() |
{ |
HANDLE hThread1, hThread2; //两个线程的handle |
DWORD ThreadId1, ThreadId2; //两个线程的线程ID |
hThread1 = CreateThread(NULL,0,Thread1,NULL,0,&ThreadId1); //创建线程1 |
if (hThread1 == NULL) |
return -1; |
hThread2 = CreateThread(NULL,0,Thread2,NULL,0,&ThreadId2); //创建线程2 |
if (hThread2 == NULL) |
return -1; |
if ( getchar ()) //按回车后终止程序运行 |
g_continue = false ; |
system ( "pause" ); |
} |
//线程1执行的代码 |
buffer bf[10]; |
DWORD WINAPI Thread1( LPVOID lpPara) |
{ |
int n=0,a=0; |
while (g_continue) |
{ |
WaitForSingleObject(hempty,INFINITE); |
WaitForSingleObject(hmutex,INFINITE); |
bf[n].bufferzt=1; |
bf[n].bufferpd=++n; |
std::cout<< "生产者将产品" <<n<< "放入缓冲单元" <<n-1<< ",缓冲队列当前状态为:" <<std::endl; |
std::cout<< "缓冲单元编号" << " 产品编号" << " 缓冲单元状态" <<std::endl; |
for (a=0;a<10;a++) |
std::cout<< " " <<a<< " " <<bf[a].bufferpd<< " " <<bf[a].bufferzt<<std::endl; |
n=n%10; |
Sleep(200); //睡眠,让出CPU使用权 |
ReleaseMutex(hmutex); |
ReleaseSemaphore(hfull,1,NULL); |
} |
return 0; |
} |
//线程2执行的代码 |
DWORD WINAPI Thread2( LPVOID lpPara) |
{ |
int spend=0,a=0; |
while (g_continue) |
{ |
WaitForSingleObject(hfull,INFINITE); |
WaitForSingleObject(hmutex,INFINITE); |
Sleep(200); //睡眠,让出CPU使用权 |
bf[spend].bufferpd=0; |
bf[spend].bufferzt=0; |
std::cout<< "消费者从冲单元" <<spend<< "将产品" <<spend+1<< "取出,缓冲队列当前状态为:" <<std::endl; |
std::cout<< "缓冲单元编号" << " 产品编号" << " 缓冲单元状态" <<std::endl; |
for (a=0;a<10;a++) |
std::cout<< " " <<a<< " " <<bf[a].bufferpd<< " " <<bf[a].bufferzt<<std::endl; |
spend=(spend+1)%10; |
ReleaseMutex(hmutex); |
ReleaseSemaphore(hempty,1,NULL); |
} |
return 0; |
} |