信号量 生产者消费者问题

来源:百度知道 编辑:UC知道 时间:2024/05/22 14:27:58
Write C/C++ programs to implement a solution to the producer-consumer
problem. The programs must fulfill the following requirements.
 Two producer threads and two consumer threads are created, as well as
two empty slots in the buffer.
 Each producer or consumer thread has a serial number, starting from 0
and each of the successors incrementing by 1.
 Each producer deposits an item in a slot. The value of the item is its serial
number.
 Each producer or consumer notifies by printing out a message when it
starts up, and prints out a message when it deposits or removes an item in
the buffer.
 The program finally prints out the number of items left in the buffer.
 Make sure all allocated memory is freed properly.

On the basis of Task 1 change your program to accept command-line arguments
for number of producers, number of consumers and number of slots. The
invocation of your program should be something l

//使用的是操作系统信号量机制
//没有写完,不打算写了

#include <stdio.h>
#include <windows.h>
#define MAXSIZE 1000000

HANDLE g_hSlotMutex;
HANDLE g_hSlot;

int g_isTerminated;
int g_iSlot[MAXSIZE];
int g_iSlotSize;

HANDLE g_hConsumer[MAXSIZE];
int g_iConsumer;

HANDLE g_hProducer[MAXSIZE];
int g_iProducer;

DWORD WINAPI ConsumerThread(PVOID pParam)
{

}

DWORD WINAPI ProducerThread(PVOID pParam)
{

}

int main(int argc,char* argv)
{
int i;
if(argc != 4)
{
printf("usage: cmd #1 #2 #3\n");
return -1;
}

sscanf(argv[1],"%d",&g_iConsumer);
sscanf(argv[2],"%d",&g_iProducer);
sscanf(argv[3],"%d",&g_iSlotSize);

g_hSlot = CreateSemaphore(
NULL,
0,
g_iSlotSize,
NULL);