您的位置:首页 > 职场人生

CriticalSection VC

2010-01-04 16:00 447 查看
还是无聊的测试,当线程间会频繁的碰撞时,可能就需要我们仔细的设计同步的检测规则,这个测试说明Interlocked系列函数比CS函数可能更具有优势。所以当我们在多线程间同步时,可以考虑把某些用CS进行同步时的规则合理的转换成 Interlocked函数。




#include "stdafx.h"




#include <windows.h>


#include <stdlib.h>


#include <stdio.h>


#include <process.h>






LONG uiCount = 0;




UINT WINAPI IOWorkerThreadProc(LPVOID pParam)






{




DWORD dTick = GetTickCount();


for(int i = 0; i < 100000000; i++)






{


::EnterCriticalSection( &m_cs );


uiCount++;


::LeaveCriticalSection( &m_cs );




}








printf("Thread dead! %d -- %d ",uiCount,GetTickCount()-dTick);




return 0xdead;


}








UINT WINAPI IOWorkerThreadProc_(LPVOID pParam)






{




DWORD dTick = GetTickCount();


for(int i = 0; i < 100000000; i++)






{


InterlockedIncrement(&uiCount);


}








printf("Thread dead! %d -- %d ",uiCount,GetTickCount()-dTick);




return 0xdead;


}














void main()






{


::InitializeCriticalSection( &m_cs );




int i = 0;




for(i = 0; i < 5; i++)






{


_beginthreadex(0,0,IOWorkerThreadProc, 0,0, NULL);


}




getchar();


printf("SUM:%d ",uiCount);


uiCount = 0;




for(i = 0; i < 5; i++)






{


_beginthreadex(0,0,IOWorkerThreadProc_, 0,0, NULL);


}






getchar();




printf("SUM:%d ",uiCount);






getchar();


::DeleteCriticalSection( &m_cs );




}

输出结果:
Thread dead! 420951825 -- 59672
Thread dead! 427460014 -- 60563
Thread dead! 433629330 -- 61391
Thread dead! 498019991 -- 70047
Thread dead! 500000000 -- 70188
SUM:500000000
Thread dead! 416899248 -- 11875
Thread dead! 435609187 -- 12344
Thread dead! 482671736 -- 13750
Thread dead! 499292047 -- 14187
Thread dead! 500000000 -- 14250
SUM:500000000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  职场 VC 休闲