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

给懒的重新打代码的人用。

// 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值