windows 互斥及临界区test-demo

// testWinLock.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include "LockMutex.h"
#include "CriSection.h"
#include <iostream>  
#include <process.h>  
#include <time.h>  


using namespace std;  


//#define ENABLE_MUTEX  
#define ENABLE_CRITICAL_SECTION  


#if defined (ENABLE_MUTEX)  
//创建一个互斥对象类型锁  
CLockMutex g_Lock;  
#elif defined (ENABLE_CRITICAL_SECTION)  
//创建一个临界区类型锁  
CCriSection g_Lock;  
#endif  




void LockCompare(int &iNum)  
{  
CMyLock lock1(g_Lock);//线程所有权判断,同线程可访问
//g_Lock.Lock();
cout<<"+";
iNum++;  
//g_Lock.Unlock();
}  


//线程函数  
unsigned int __stdcall StartThread(void *pParam)  
{  
char *pMsg = (char *)pParam;  
if (!pMsg)  
{  
return (unsigned int)1;  
}  
cout<<"============="<<pMsg<<endl;
CMyLock lock2(g_Lock);  
//g_Lock.Lock();
cout<<"============="<<pMsg<<"locked"<<endl;
clock_t tStart,tEnd;  


tStart = clock();  
int iNum = 0;  
for (int i = 0; i < 100; i++)  
{  
LockCompare(iNum);  
}  
tEnd = clock();  


#if defined (ENABLE_MUTEX)  
cout<<"The lock type is mutex, time = "<<(tEnd - tStart)<<" ms."<<endl;  
#elif defined (ENABLE_CRITICAL_SECTION)  
cout<<"The lock type is critical section, time = "<<(tEnd - tStart)<<" ms."<<endl;  
#endif  
//g_Lock.Unlock();
return (unsigned int)0;  
}  




int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread1, hThread2;  
    unsigned int uiThreadId1, uiThreadId2;  
  
    char *pMsg1 = "First print thread.";  
    char *pMsg2 = "Second print thread.";  
  
    //创建两个工作线程,分别打印不同的消息  
    hThread1 = (HANDLE)_beginthreadex(NULL, 0, &StartThread, (void *)pMsg1, 0, &uiThreadId1);  
    hThread2 = (HANDLE)_beginthreadex(NULL, 0, &StartThread, (void *)pMsg2, 0, &uiThreadId2);  
  
    //等待线程结束  
    DWORD dwRet = WaitForSingleObject(hThread1,INFINITE);  
    if ( dwRet == WAIT_TIMEOUT )  
    {  
        TerminateThread(hThread1,0);  
    }  
    dwRet = WaitForSingleObject(hThread2,INFINITE);  
    if ( dwRet == WAIT_TIMEOUT )  
    {  
        TerminateThread(hThread2,0);  
    }  
  
    //关闭线程句柄,释放资源  
    ::CloseHandle(hThread1);  
    ::CloseHandle(hThread2);  
  
    system("pause");  
    return 0;  

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

字正腔圆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值