多线程编程

#include "stdafx.h"

#include <Windows.h>  
#include <iostream>  

using namespace std;  

static int g_iCnt = 100;
CRITICAL_SECTION g_CriticalSection;

DWORD WINAPI Thread1(LPVOID lpParmeter);  
DWORD WINAPI Thread2(LPVOID lpParmeter);  

int main()  
{  
	HANDLE hThread1 ;  
	HANDLE hThread2 ;  

	InitializeCriticalSection(&g_CriticalSection);

	hThread1 = CreateThread(NULL, 0, Thread1, NULL, 0, NULL);  
	hThread2 = CreateThread(NULL, 0, Thread2, NULL, 0, NULL);  

	HANDLE h[2]={hThread1,hThread2};
	//等待线程退出
	DWORD ret = WaitForMultipleObjects(2,h,TRUE,INFINITE);
	switch(ret)
	{
	case WAIT_TIMEOUT:
		cout<<"WAIT_TIMEOUT"<<endl;
		break;
	case WAIT_FAILED:
		cout<<"WAIT_FAILED"<<endl;
		break;
	default:
		cout<<"Success!"<<endl;
		break;
	}

	CloseHandle(hThread1);  
	CloseHandle(hThread2);  
	DeleteCriticalSection(&g_CriticalSection);          // 删除  
	system("PAUSE");  
	return 0;  
}  

DWORD WINAPI Thread1(LPVOID lpParmeter)  
{  
	int t = 100; 
	while (t > 0) 
	{  
		//进入临界区,获得所有权,其他线程就等  
		EnterCriticalSection(&g_CriticalSection);      
		t = g_iCnt ; //这才是临界区里面应该做的事情。
		if (t > 0)
		{  
			cout << "Thread1:" << g_iCnt-- << endl; 
		}  
		LeaveCriticalSection(&g_CriticalSection);   
		Sleep(20);  //不能在临界区里等待
	}  
	return 0;  
}  

DWORD WINAPI Thread2(LPVOID lpParameter)//thread data  
{  
	int t = 100; 
	while (t > 0)
	{  
		EnterCriticalSection(&g_CriticalSection);  
		t = g_iCnt;
		if (t > 0)
		{  
			cout << "thread2:" << g_iCnt-- << endl;   
		}  
		LeaveCriticalSection(&g_CriticalSection);  
		Sleep(20);
	}  
	return 0;  
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值