加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – Win32关键部分与互斥性能

发布时间:2020-12-16 10:53:08 所属栏目:百科 来源:网络整理
导读:我写了一个小程序来比较 Windows中Critical Section vs Mutex的性能. 在我跑的测试中,获得关键部分似乎更慢:O任何人都可以解释为什么两件事花费的时间差不多,以及内部发生了什么. 这是我使用的计时器 – http://cplus.about.com/od/howtodothingsi2/a/timin
我写了一个小程序来比较 Windows中Critical Section vs Mutex的性能.

在我跑的测试中,获得关键部分似乎更慢:O任何人都可以解释为什么两件事花费的时间差不多,以及内部发生了什么.

这是我使用的计时器 – http://cplus.about.com/od/howtodothingsi2/a/timing.htm

#include "stdafx.h"
#include<iostream>
#include<vector>
#include "h_timer.h"
#include<WinBase.h>
#include<Windows.h>
#include<stdio.h>

#define MAX_THREADS 2000  
//Comment and Uncomment this to enable/disable critialSection / Mutex
#define CRIT 1

using namespace std;

HANDLE Mutex;
CRITICAL_SECTION critSection;
DWORD WINAPI Contention( LPVOID );

int main( void )
{
    HANDLE Thread[MAX_THREADS];
    DWORD ThreadID;
    int i;

#ifdef CRIT
//create a critical section
InitializeCriticalSection(&critSection);
#else

    // Create a mutex with no initial owner
    Mutex = CreateMutex( NULL,FALSE,NULL);

#endif

    // Create worker threads

CStopWatch timer,tempTimer;
timer.startTimer();
    for( i=0; i < MAX_THREADS; i++ )
    {
        Thread[i] = CreateThread( NULL,(LPTHREAD_START_ROUTINE)Contention,NULL,&ThreadID);
    }
    WaitForMultipleObjects(MAX_THREADS,Thread,TRUE,INFINITE);

    timer.stopTimer();
    cout<<endl<<"Elapsed Time:"<<timer.getElapsedTime();
    cin.get();
    // Close thread and mutex handles

    for( i=0; i < MAX_THREADS; i++ )
    CloseHandle(Thread[i]);

    CloseHandle(Mutex);
    return 0;
}


DWORD WINAPI Contention( LPVOID lpParam )
{
    #ifdef CRIT
EnterCriticalSection(&critSection);
//printf("ThreadId: %dn",GetCurrentThreadId());
//printf("Let's try Again. %dnn",GetCurrentThreadId());
LeaveCriticalSection(&critSection);

#else
// lpParam not used in this example
    UNREFERENCED_PARAMETER(lpParam);
    DWORD dwCount=0,dwWaitResult;

    // Request ownership of mutex.
    dwWaitResult = WaitForSingleObject(
            ghMutex,// handle to mutex
            INFINITE); // no time-out interval
        dwCount++;
    ReleaseMutex(ghMutex);
#endif

return TRUE;
}

对于2000线程,在四核HPZ210上,两者都需要大约1.5秒.

解决方法

我认为有两个因素:

主要是 – 您的程序由线程创建开销主导.您正在创建和销毁2000个线程,并且每个线程仅访问一次互斥锁/ CS.创建线程所花费的时间淹没了锁定/解锁时间的差异.

另外 – 您可能没有测试这些锁被优化的用例.尝试生成两个线程,每个线程尝试访问互斥锁/ CS数千次.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读