摘要:本文主要向大家介绍了VC编程之CriticalSection VC,通过具体的内容向大家展示,希望对大家学习VC编程有所帮助。
本文主要向大家介绍了VC编程之CriticalSection VC,通过具体的内容向大家展示,希望对大家学习VC编程有所帮助。
还是无聊的测试,当线程间会频繁的碰撞时,可能就需要我们仔细的设计同步的检测规则,这个测试说明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/MFC的学习,希望对VC/MFC有兴趣的朋友有所帮助。了解更多内容,请关注职坐标编程语言VC/MFC频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号