您的位置:首页 > 其它

线程同步的3种实现方法 互斥对象 临界资源 事件对象

2015-05-22 13:37 309 查看
给懒的重新打代码的人用。

// Win32 Console.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;

CRITICAL_SECTION g_cs;
HANDLE g_hMutex;
HANDLE g_hEvent;

DWORD WINAPI ThreadProc1(LPVOID lpParam)
{
	WaitForSingleObject(g_hEvent, INFINITE);
//	WaitForSingleObject(g_hMutex, INFINITE);
//	EnterCriticalSection(&g_cs);
	cout << "----1111111-------" << endl;
//	LeaveCriticalSection(&g_cs);
//	ReleaseMutex(g_hMutex);
	SetEvent(g_hEvent);
	return 0;
}

DWORD WINAPI ThreadProc2(LPVOID lpParam)
{
	WaitForSingleObject(g_hEvent, INFINITE);
//	WaitForSingleObject(g_hMutex, INFINITE);
//	EnterCriticalSection(&g_cs);
	cout << "----2222222-------" << endl;
//	LeaveCriticalSection(&g_cs);LeaveCriticalSection(&g_cs);
//	ReleaseMutex(g_hMutex);
	SetEvent(g_hEvent);
	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
//	InitializeCriticalSection(&g_cs);
//	g_hMutex = CreateMutex(NULL, TRUE, NULL);
	g_hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

	DWORD idThread1 = -1;
	DWORD idThread2 = -1;
	DWORD param;

	HANDLE hThread1 = CreateThread(NULL, 0, ThreadProc1, (LPVOID)¶m, 0, &idThread1);
	CloseHandle(hThread1);

	HANDLE hThread2 = CreateThread(NULL, 0, ThreadProc2, (LPVOID)¶m, 0, &idThread2);
	CloseHandle(hThread2);

//	EnterCriticalSection(&g_cs);
	cout << "idThread1:" << idThread1 << endl;
	cout << "idThread2:" << idThread2 << endl;

	SetEvent(g_hEvent);
//	LeaveCriticalSection(&g_cs);
//	ReleaseMutex(g_hMutex);

	system("pause");
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: