CreateMutex

#include <stdio.h>
#include <windows.h>

DWORD WINAPI ThreadProc1(LPVOID lpParameter);
DWORD WINAPI ThreadProc2(LPVOID lpParameter);

int sum=100;
HANDLE hMutex=NULL;

int main (void)
{
	HANDLE Thread[2]={0};
	Thread[0]=CreateThread(NULL,NULL,ThreadProc1,NULL,NULL,NULL);
	Thread[1]=CreateThread(NULL,NULL,ThreadProc2,NULL,NULL,NULL);
	CloseHandle(Thread[0]);
	CloseHandle(Thread[1]);
	hMutex=CreateMutex(NULL,FALSE,NULL);  
	//TRUE代表主线程拥有互斥对象 但是主线程没有释放该对象  互斥对象谁拥有 谁释放
	//FLASE代表当前没有线程拥有这个互斥对象
	if (hMutex==NULL)
	{
		return 0;
	}
	getchar();

	return 0;
}

DWORD WINAPI ThreadProc1( LPVOID lpParameter )
{
	while(true)
	{
		WaitForSingleObject(hMutex,INFINITE);    //等待对象是在信号状态
		if (sum>0)
		{
			Sleep(1);
			printf("Thread1 %d\n",sum--); 
		}
		else
			break;
		ReleaseMutex(hMutex);                    //释放互斥对象所有权 
	}

	return true;
}

DWORD WINAPI ThreadProc2( LPVOID lpParameter )
{
	while(true)
	{
		WaitForSingleObject(hMutex,INFINITE);    //等待对象是在信号状态
		if (sum>0)
		{
			Sleep(1);
			printf("Thread2 %d\n",sum--);
		}
		else
			break;
		ReleaseMutex(hMutex);                    //释放互斥对象所有权
	}

	return true;
}
/*
2015年8月2日 17:03:36
程序执行结果如下
Thread1 100
Thread2 99
Thread1 98
Thread2 97
Thread1 96
Thread2 95
Thread1 94
Thread2 93
Thread1 92
Thread2 91
Thread1 90
Thread2 89
Thread1 88
Thread2 87
Thread1 86
Thread2 85
Thread1 84
Thread2 83
Thread1 82
Thread2 81
Thread1 80
Thread2 79
Thread1 78
Thread2 77
Thread1 76
Thread2 75
Thread1 74
Thread2 73
Thread1 72
Thread2 71
Thread1 70
Thread2 69
Thread1 68
Thread2 67
Thread1 66
Thread2 65
Thread1 64
Thread2 63
Thread1 62
Thread2 61
Thread1 60
Thread2 59
Thread1 58
Thread2 57
Thread1 56
Thread2 55
Thread1 54
Thread2 53
Thread1 52
Thread2 51
Thread1 50
Thread2 49
Thread1 48
Thread2 47
Thread1 46
Thread2 45
Thread1 44
Thread2 43
Thread1 42
Thread2 41
Thread1 40
Thread2 39
Thread1 38
Thread2 37
Thread1 36
Thread2 35
Thread1 34
Thread2 33
Thread1 32
Thread2 31
Thread1 30
Thread2 29
Thread1 28
Thread2 27
Thread1 26
Thread2 25
Thread1 24
Thread2 23
Thread1 22
Thread2 21
Thread1 20
Thread2 19
Thread1 18
Thread2 17
Thread1 16
Thread2 15
Thread1 14
Thread2 13
Thread1 12
Thread2 11
Thread1 10
Thread2 9
Thread1 8
Thread2 7
Thread1 6
Thread2 5
Thread1 4
Thread2 3
Thread1 2
Thread2 1

*/


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值