简单进程同步的解决

关键技术: 创建两个事件  CreateEvent,  创建一个事件 CreateEvent 是无法解决问题的


// 20171228_01.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

CRITICAL_SECTION cs;
DWORD g_Number = 0;
int g_Max = 10;
HANDLE hMutex;
HANDLE hEvent_Create;
HANDLE hEvent_User;

DWORD WINAPI ThreadProc1(
						LPVOID lpParameter   // thread data
)
{
	//生产者
	for(int i=0;i<g_Max;i++)
	{
		//EnterCriticalSection(&cs);
		
		WaitForSingleObject(hEvent_Create,INFINITE);
		g_Number = 1;
		DWORD id = GetCurrentThreadId();
		printf("生产者 %d 的数据 %d 放入缓冲区 \n",id, g_Number);
		//SetEvent(hEvent);
		//ResetEvent(hEvent);
		SetEvent(hEvent_User);
		Sleep(110);
		//ReleaseMutex(hMutex);
		//LeaveCriticalSection(&cs);
	}


	return 0;
}

DWORD WINAPI ThreadProc2(
						 LPVOID lpParameter   // thread data
						 )
{
	//消费者
	for(int i=0;i<g_Max;i++)
	{
		//EnterCriticalSection(&cs);
		//WaitForSingleObject(hMutex,INFINITE);
		WaitForSingleObject(hEvent_User,INFINITE);
		g_Number = 0;
		DWORD id = GetCurrentThreadId();
		printf("---------消费者 %d 的数据 %d 放入缓冲区 \n",id, g_Number);
		SetEvent(hEvent_Create);
		Sleep(100);
		//LeaveCriticalSection(&cs);
		//ReleaseMutex(hMutex);
	}
	
	
	return 0;
}


int main(int argc, char* argv[])
{

	//printf("he111\n");
	//测试生产者和消费者的问题
	
	//EnterCriticalSection()

	//InitializeCriticalSection(&cs);

	//hMutex = CreateMutex(NULL,FALSE,"XYZ");
	//OpenMutex()
	//OpenMutex()

	
	HANDLE hThread[2];
	hThread[0] = CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);
	hThread[1] = CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);

	hEvent_Create = CreateEvent(NULL,FALSE,TRUE,NULL);
	hEvent_User = CreateEvent(NULL,FALSE,FALSE,NULL);

	WaitForMultipleObjects(2,hThread,TRUE,INFINITE);


	CloseHandle(hThread[0]);
	CloseHandle(hThread[1]);



	printf("main ..... end........\n");
	
	//DeleteCriticalSection(&cs);
	return 0;
}

原文链接: 简单进程同步的解决 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-352.html )

发表评论

0则评论给“简单进程同步的解决”