windows多线程同步

#include <WINDOWS.H>
#include <IOSTREAM>

using namespace std;

DWORD WINAPI Fun1Proc(LPVOID lpParameter);
DWORD WINAPI Fun2Proc(LPVOID lpParameter);

int index = 0;
int ticket = 100;
HANDLE g_hMutex;

int main()
{
	HANDLE hThread1;
	HANDLE hThread2;
	hThread1 = CreateThread(NULL,//安全性设置
		0,//指定初始化栈大小
		Fun1Proc,//函数地址
		NULL,//指定单独的参数
		0,//指定这个纯种创建的标志,0立即运行
		NULL//指定一个变量,接受该线程的标识符
		);
	hThread2 = CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);

	CloseHandle(hThread1);//关闭线程,并没有终止线程,只是关闭其引用
	CloseHandle(hThread2);

	while(TRUE)
	{
		Sleep(1000);
		cout << "main thread is running" << endl;
		Sleep(1000);
	}

	g_hMutex = CreateMutex(NULL,TRUE,NULL);
	WaitForSingleObject(g_hMutex,INFINITE);
	ReleaseMutex(g_hMutex);

	return 0;
}

DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
	while(TRUE)
	{
		WaitForSingleObject(g_hMutex,INFINITE);
		
		if (ticket>0)
		{
			Sleep(1000);
			cout << "thread 1 sell ticket: " << ticket-- << endl;
		}
		else
		{
			break;
		}
	}
	
	return 0;
}

DWORD WINAPI Fun2Proc(LPVOID lpParameter)
{
	while(TRUE)
	{
		WaitForSingleObject(g_hMutex,INFINITE);

		if (ticket>0)
		{
			Sleep(1000);
			cout << "thread 2 sell ticket: " << ticket-- << endl;
		}
		else
		{
			break;
		}

		ReleaseMutex(g_hMutex);
	}
	
	return 0;
}

你可能感兴趣的:(windows多线程同步)