多线程-临界区

函数功能:初始化

函数原型:

void InitializeCriticalSection(LPCRITICAL_SECTIONlpCriticalSection);

函数说明:定义关键段变量后必须先初始化。

 

函数功能:销毁

函数原型:

void DeleteCriticalSection(LPCRITICAL_SECTIONlpCriticalSection);

函数说明:用完之后记得销毁。

 

函数功能:进入关键区域

函数原型:

void EnterCriticalSection(LPCRITICAL_SECTIONlpCriticalSection);

函数说明:系统保证各线程互斥的进入关键区域。

 

函数功能:离开关关键区域

函数原型:

void LeaveCriticalSection(LPCRITICAL_SECTIONlpCriticalSection);

 

输出将范文tickets设置为临界资源,由两个进程轮流访问

#include<stdio.h>
#include<process.h>
#include<windows.h>
int tickets=50;
CRITICAL_SECTION g_cs;
unsigned int __stdcall Fun1(VOID *lp)
{	
	while(true)
	{
                Sleep(1);//这个要在临界区外面,不然要了资源切换了线程导致浪费
		EnterCriticalSection(&g_cs);
	
		if(tickets>0)
		{
			printf("thread1 %d\n",tickets--);
			LeaveCriticalSection(&g_cs);
		}
		else
		{
			LeaveCriticalSection(&g_cs);
			break;
		}
	}
	return 0;
}
unsigned int __stdcall Fun2(VOID *lp)
{
	while(true)
	{
                Sleep(1);
		EnterCriticalSection(&g_cs);
		if(tickets>0)
		{
			printf("thread2 %d\n",tickets--);
			LeaveCriticalSection(&g_cs);
		}
		else
		{
			LeaveCriticalSection(&g_cs);
			break;
		}
	}
	return 0;
}
int main()
{
InitializeCriticalSection(&g_cs);//初始化要在定义handle前面,不然调用了线程可能临界区并没有初始化
HANDLE handle1,handle2;
handle1=(HANDLE)_beginthreadex(NULL,0,Fun1,NULL,0,NULL);
handle2=(HANDLE)_beginthreadex(NULL,0,Fun2,NULL,0,NULL);
CloseHandle(handle1);
CloseHandle(handle2);

Sleep(4000);
DeleteCriticalSection(&g_cs);
return 0;
}

  

posted @ 2014-09-19 12:35  calmound  阅读(573)  评论(0编辑  收藏  举报