hello,多线程。

#include <windows.h>
#include <iostream.h>

//声明线程入口函数原型
DWORD WINAPI Fun1Proc(
  LPVOID lpParameter
);

DWORD WINAPI Fun2Proc(
  LPVOID lpParameter
);

int tickets = 100;

HANDLE hMutex;

void main()
{
	hMutex = CreateMutex(NULL,FALSE,NULL);//创建一个匿名的互斥对象(注意要先于创建线程)
	
	HANDLE  hThread1,hThread2;
	hThread1 = CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
	CloseHandle(hThread1);
	
	hThread2 = CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);	
	CloseHandle(hThread2);

/*
	hMutex = CreateMutex(NULL, FALSE,"MuName);//创建一个命名的互斥对象
	if(hMutex)
	{
		if(ERROR_ALREADY_EXISTS == GetLastError())
		{
			cout<<"已有一个实例在运行了,只能有一个实例同时运行。"<<endl;
			return;
		}
	}
*/
	Sleep(4000);
}
/*------------实现线程入口函数Fun1Proc---------------*/
DWORD WINAPI Fun1Proc(
  LPVOID lpParameter
)
{	
	while(TRUE)
	{
		WaitForSingleObject(hMutex,INFINITE);//请求互斥对象
		if(tickets>0)
		{
			Sleep(1);
			cout<<"thread1 sell tickets: "<<tickets--<<endl;
		}
		else  
			break;
		ReleaseMutex(hMutex);
	}
	return 0;
}

/*-----------实现线程入口函数Fun2Proc--------------*/
DWORD WINAPI Fun2Proc(
  LPVOID lpParameter
)
{	
	while(TRUE)
	{
		WaitForSingleObject(hMutex,INFINITE);
		if(tickets>0)
		{
			Sleep(1);
			cout<<"thread2 sell tickets: "<<tickets--<<endl;
		}
		else
			break;
		ReleaseMutex(hMutex);
	}
	return 0;
}

线程同步的方式:

1。互斥对象。(CreateMutex)

2。互斥对象。(CreateEvent)

3。关键代码段。(InitializeCriticalSection)

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