首页 > 代码库 > 在VC6.0中多线程编程示例(带同步信号量)

在VC6.0中多线程编程示例(带同步信号量)

直接上代码:
#include <windows.h>//必要的头文件,使用Windows API函数
#include <stdio.h>

int index = 0;
int tickets = 100;//票数
HANDLE hMutex; //使用全局的互斥对象来保证对同一资源的互斥访问与操作这里是tickets
//线程处理函数原型,形式可从MSDN中拷贝

//线程1 的入口函数

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

void main()
{
	HANDLE hThread1;
	DWORD thread1ID;
	//创建线程1
	hThread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, &thread1ID);
	HANDLE hThread2;
	DWORD thread2ID;
	//创建线程2
	hThread2 = CreateThread(NULL, 0, Fun2Proc, NULL, 0, &thread2ID);
	CloseHandle(hThread1); //关闭线程的句柄,为什么要关闭?它将线程的使用计数减1
	CloseHandle(hThread2);//这样当线程结束时,线程内核对象被释放,
	//否则只有当进程结束,才释放线程的内核对象hThread1与hThread
    //创建一个互斥对象,如果成功返回互斥对象的句柄,否则返回NULL
	hMutex = CreateMutex(NULL, FALSE, "tickets");
	if (hMutex)	
	{	
		if(ERROR_ALREADY_EXISTS == GetLastError())		
		{		
			puts("only one instance can run!");		
			return;		
		}	
	}
	Sleep(4000);//主线程睡眠4秒钟,给其它线程运行的时间,因为一旦主线程退出则进行退出,其它线程也将退出
}

DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
	while(TRUE)
	{
		WaitForSingleObject(hMutex, INFINITE);//如果全局互斥对象是有信号状态,则获得该对象,
		//直到调用ReleaseMutex之前,互斥对象是无信号状态,其它线程不能对互斥对象进行访问
		if(tickets > 0)	
		{
			Sleep(1);
			printf("Thread1 sell tickets : %d\n", tickets-- );
		}
		else
			break;
		ReleaseMutex(hMutex);//将互斥对象设置为有信号状态
		
	}
	return 0;
	
}
DWORD WINAPI Fun2Proc(LPVOID lpParameter)				  
{      
	while(TRUE)
	{
		WaitForSingleObject(hMutex, INFINITE);
		if (tickets > 0)
		{	
			Sleep(1);
			printf("Thread2 sell tickets : %d\n", tickets-- );
		}
		else
			break;
		ReleaseMutex(hMutex);
		}
	return 0;
}