当前位置:文档之家› 操作系统-信号量C++代码WIN32

操作系统-信号量C++代码WIN32

#include
#include
#include
#include
#include

#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int cnt = 0; //现有产品数量

HANDLE Mutex , //互斥锁
Empty, //信号量emp
Full; //信号量full

void init()
{
Mutex = CreateMutex(NULL, FALSE, NULL);//互斥锁初始化
Empty = CreateSemaphore(NULL, 5, 5, NULL);//信号量Emp初始化
Full = CreateSemaphore(NULL, 0, 5, NULL);//信号量Full初始化
}

int insert_item(int item, int order)
{//insert item into buffer
int flag = -1;
WaitForSingleObject(Empty, INFINITE);
WaitForSingleObject(Mutex, INFINITE);

//critical section
if(cnt < BUFFER_SIZE){
buffer[cnt++] = item;
flag = 0;//insert successfully
printf("producer %d produced %d\n", order, cnt);
}

ReleaseMutex(Mutex);
ReleaseSemaphore(Full, 1, NULL);

return flag;
}

int remove_item(int &item, int order)
{//remove object from buffer and place it in item
int flag = -1;
WaitForSingleObject(Full, INFINITE);
WaitForSingleObject(Mutex, INFINITE);

//critical section
if(cnt > 0)
{
item = buffer[cnt-1];
buffer[cnt-1] = 0;
flag = 0;
printf("consumer %d consumed %d\n",order,cnt);
cnt--;
}

ReleaseMutex(Mutex);
ReleaseSemaphore(Empty, 1, NULL);

return flag;
}

DWORD WINAPI producer(void *param)
{
srand((unsigned)time(NULL)); //seed
int random;
while(true)
{
Sleep((rand()%10 + 1) * 1000);
random = rand() % 50 + 1;
if(insert_item(random, (DWORD)param))
printf("report error condition\n");
}
}

DWORD WINAPI consumer(void *param)
{
srand((unsigned)time(NULL)); //seed
int random;
while(true)
{
Sleep((rand()%10 + 1) * 1000);
if(remove_item(random,(DWORD)param))
printf("report error condition\n");
}
}

int main(int argc, char *argv[])
{
init(); //intialize semaphores
static const int sleepTime = 10000, //睡眠多长时间终止
producerThs = 10, //生产者线程数量
consumerThs = 10; //消费者线程数量

memset(buffer, 0, sizeof buffer); //缓存区初始化


DWORD ProducerThreadId[producerThs],
ConsumerThreadId[consumerThs];
HANDLE ProducerThreadHandles[producerThs],
ConsumerThreadHandles[consumerThs];
int i;
for(i = 0; i < producerThs; ++i)
{
//创建生产者线程
ProducerThreadHandles[i] = CreateThread(
NULL,
0,
producer, //线程函数
(LPVOID)i, //传递给线程函数的参数
0,
&ProducerThreadId[i]);
}

for(i = 0; i < consumerThs; ++i)
{
//创建消费者线程
ConsumerThreadHandles[i] = CreateThread(
NULL,
0,
consumer, //线程函数
(LPVOID)i, //传递给线程函数的参数
0,
&ConsumerThreadId[i]);
}

Sleep(sleepTime);//主函数睡眠

//关闭所有子线程
for(i = 0; i < producerThs; ++i){
CloseHandle(ProducerThreadHandles[i]);
CloseHandle(ConsumerThreadHandles[i]);
}

//exit

(0);//终止应用程序

system("pause");
return 0;
}

相关主题
文本预览
相关文档 最新文档