用信号量生产者消费者模式

前言

  用队列和信号量实现生产者消费者模式.队列代码在这里

代码

#include "reLink.h"
#include <Windows.h>


struct node *pHead;									//声明全局队列指针

DWORD WINAPI product(void *p)								//生产者
{
	pHead = enqueue(pHead, 0);
	int i = 0;
	while (++i)
	{
		//打开信号量
		HANDLE semaphore = OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, TRUE, "xiaoY");
		//等待信号量
		WaitForSingleObject(semaphore, INFINITE);
		//进入队列
		pHead = enqueue(pHead, i);
		printf("生产者生产 %4d\n", i);
	}
	return 0;
}


DWORD WINAPI consumer(void *p)								//消费者
{
	int i = 0;
	while (++i)
	{
		MessageBoxA(0, "wait", "wait", 0);
		int num;
		pHead = dequeue(pHead, &num);
		printf("消费者消费 %4d\n", num);

		//根据name打开信号量
		HANDLE semaphore = OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, TRUE, "xiaoY");
		ReleaseSemaphore(semaphore, 1, NULL);
	}
	return 0;
}

int main(int argc, char *argv[])
{
	//初始化队列
	init(&pHead);					
	//创建信号量并指定name,打开信号量需要根据name打开
	HANDLE semaphore = CreateSemaphore(NULL, 0, 1, "xiaoY");
	//创建线程,调用生产者
	HANDLE hProduct = CreateThread(NULL, 0, product, NULL, 0, NULL);
	//创建线程,调用消费者
	HANDLE hConsumer = CreateThread(NULL, 0, consumer, NULL, 0, NULL);

	getchar();
	CloseHandle(semaphore);
	CloseHandle(hProduct);
	CloseHandle(hConsumer);		
	return 0;
}


秋风 2017-01-12