最近操作系统的实验课,老师非要让Windows的有关线程API去模拟实现生产者消费者问题,之前没接触过这些,看了好久的MSDN,大致懂了流程,可是还是会出现一些问题。下面是源代码,也不长,肯定熟悉这方面的大神给运行下调试调试啊,谢谢了。#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;const int MaxBufferSize = 5; //最大缓冲区数目
int gi_In = 0;  //往缓冲区中写内容下标
int gi_Out = 0;  //从缓冲区中国读出内容下标#define FULL 1
#define EMPTY 0const int MaxThreadNum = 1;
int gi_Buffer[MaxBufferSize] = { EMPTY }; //表示空(empty)状态typedef struct
{
HANDLE hMutexHandle;
HANDLE hEmptyHandle;
HANDLE hFullHandle;
}PARAMS,*PPARAMS;void Producer( PVOID pvoid)
{
DWORD dwWaitResult;
while(TRUE)
{
volatile PPARAMS pparams=(PPARAMS)pvoid; dwWaitResult = WaitForSingleObject(pparams->hEmptyHandle, INFINITE);
WaitForSingleObject(pparams->hMutexHandle, INFINITE);
gi_Buffer[gi_In] = FULL;
gi_In = (gi_In + 1) % MaxBufferSize;
cout<<"gi_In = "<<gi_In<<endl;
ReleaseMutex(pparams->hMutexHandle);
Sleep(1000);
ReleaseSemaphore(pparams->hFullHandle, 1, NULL);
}
}void Consumer(PVOID pvoid)
{
while(TRUE)
{
volatile PPARAMS pparams=(PPARAMS)pvoid; WaitForSingleObject(pparams->hFullHandle, INFINITE);
WaitForSingleObject(pparams->hMutexHandle, INFINITE);
gi_Buffer[gi_Out] = EMPTY;
gi_Out = (gi_Out + 1) % MaxBufferSize;
cout<<"gi_Out = "<<gi_Out<<endl;
ReleaseMutex(pparams->hMutexHandle);
Sleep(1000);
ReleaseSemaphore(pparams->hEmptyHandle, 1, NULL);
}
}int main(int argc, TCHAR* argv[], TCHAR* envp[])
{
PARAMS params;
params.hMutexHandle = CreateMutex(NULL, FALSE, NULL);
params.hEmptyHandle = CreateSemaphore(NULL, 2, 2, (LPCWSTR)"emptySemaphore");
params.hFullHandle = CreateSemaphore(NULL, 0, 2, (LPCWSTR)"fullSemaphore"); HANDLE haThreads[2 * MaxThreadNum];  //线程集合
DWORD ThreadID;
//前MaxThreadNum个线程执行Producer()函数
for(int i = 0; i < MaxThreadNum; i++ )
{
haThreads[i] = CreateThread( 
NULL,       // default security attributes
0,          // default stack size
(LPTHREAD_START_ROUTINE) Producer, 
NULL,       // no thread function arguments
0,          // default creation flags
&ThreadID); // receive thread identifier if( haThreads[i] == NULL )
{
printf("CreateProducerThread error: %d\n", GetLastError());
return 1;
}
}
//后MaxThreadNum个线程执行Consumer
for (int i = MaxThreadNum; i < 2 * MaxThreadNum; i++)
{
haThreads[i] = CreateThread( 
NULL,       // default security attributes
0,          // default stack size
(LPTHREAD_START_ROUTINE) Consumer, 
NULL,       // no thread function arguments
0,          // default creation flags
&ThreadID); // receive thread identifier if( haThreads[i] == NULL )
{
printf("CreateConsumerThread error: %d\n", GetLastError());
return 1;
}
} WaitForMultipleObjects(MaxThreadNum, haThreads, TRUE, INFINITE);
}
多线程