【记录复查】mutex | critical section

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

DWORD WINAPI myfun1(LPVOID ipParameter);
DWORD WINAPI myfun2(LPVOID ipParameter);
CRITICAL_SECTION m_Sec;
int a = 0;
int main() {
	InitializeCriticalSection(&m_Sec);
	HANDLE h1, h2;
	h1 = ::CreateThread(NULL, 0, myfun1, NULL, 0, NULL);
	printf("Thread1 starts!\r\n");
	h2 = ::CreateThread(NULL, 0, myfun2, NULL, 0, NULL);
	printf("Thread2 starts!\r\n");
	::CloseHandle(h1);
	::CloseHandle(h2);
	cout << "Sleep 1s" << endl;
	::Sleep(1000);
	DeleteCriticalSection(&m_Sec);

	return 0;
}

DWORD WINAPI myfun1(LPVOID ipParameter) {
//	EnterCriticalSection(&m_Sec);
//	++a;
//	printf("%d", a);
//	LeaveCriticalSection(&m_Sec);
	while(1) {
		EnterCriticalSection(&m_Sec);
		++a;
		if(a > 200) {
			LeaveCriticalSection(&m_Sec);
			break;
		}
		printf("thread1: %d\n", a);
		LeaveCriticalSection(&m_Sec);
	}

	return 0;
}

DWORD WINAPI myfun2(LPVOID ipParameter) {
//	EnterCriticalSection(&m_Sec);
//	++a;
//	printf("%d", a);
//	LeaveCriticalSection(&m_Sec);
	while(1) {
		EnterCriticalSection(&m_Sec);
		++a;
		if(a > 200) {
			LeaveCriticalSection(&m_Sec);
			break;
		}
		printf("thread2: %d\n", a);
		LeaveCriticalSection(&m_Sec);
	}

	return 0;
}



你可能感兴趣的:(【记录复查】mutex | critical section)