互斥与关键部分有什么区别? [英] What is the difference between mutex and critical section?

查看:361
本文介绍了互斥与关键部分有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请从Linux,Windows角度进行解释?

Please explain from Linux, Windows perspectives?

我正在用C#编程,这两个术语会有所不同吗?请尽可能多地张贴带有示例之类的东西....

I am programming in C#, would these two terms make a difference. Please post as much as you can, with examples and such....

谢谢

推荐答案

对于Windows,关键部分的权重比互斥体轻.

For Windows, critical sections are lighter-weight than mutexes.

Mutexes可以在进程之间共享,但始终会导致对内核的系统调用,这会产生一些开销.

Mutexes can be shared between processes, but always result in a system call to the kernel which has some overhead.

关键部分只能在一个进程中使用,但具有的优势是,它们仅在争用的情况下才切换到内核模式-无竞争的获取(这是常见的情况)非常快.在争用的情况下,它们进入内核以等待某些同步原语(例如事件或信号量).

Critical sections can only be used within one process, but have the advantage that they only switch to kernel mode in the case of contention - Uncontended acquires, which should be the common case, are incredibly fast. In the case of contention, they enter the kernel to wait on some synchronization primitive (like an event or semaphore).

我写了一个快速的示例应用程序,比较了两者之间的时间.在我的系统中,要进行1,000,000次无竞争的获取和发布,互斥体将占用一秒钟的时间.关键部分大约需要50毫秒才能完成1,000,000次采集.

I wrote a quick sample app that compares the time between the two of them. On my system for 1,000,000 uncontended acquires and releases, a mutex takes over one second. A critical section takes ~50 ms for 1,000,000 acquires.

这是测试代码,如果互斥是第一个或第二个,我会运行此代码并获得相似的结果,因此我们看不到任何其他效果.

Here's the test code, I ran this and got similar results if mutex is first or second, so we aren't seeing any other effects.

HANDLE mutex = CreateMutex(NULL, FALSE, NULL);
CRITICAL_SECTION critSec;
InitializeCriticalSection(&critSec);

LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
LARGE_INTEGER start, end;

// Force code into memory, so we don't see any effects of paging.
EnterCriticalSection(&critSec);
LeaveCriticalSection(&critSec);
QueryPerformanceCounter(&start);
for (int i = 0; i < 1000000; i++)
{
    EnterCriticalSection(&critSec);
    LeaveCriticalSection(&critSec);
}

QueryPerformanceCounter(&end);

int totalTimeCS = (int)((end.QuadPart - start.QuadPart) * 1000 / freq.QuadPart);

// Force code into memory, so we don't see any effects of paging.
WaitForSingleObject(mutex, INFINITE);
ReleaseMutex(mutex);

QueryPerformanceCounter(&start);
for (int i = 0; i < 1000000; i++)
{
    WaitForSingleObject(mutex, INFINITE);
    ReleaseMutex(mutex);
}

QueryPerformanceCounter(&end);

int totalTime = (int)((end.QuadPart - start.QuadPart) * 1000 / freq.QuadPart);

printf("Mutex: %d CritSec: %d\n", totalTime, totalTimeCS);

这篇关于互斥与关键部分有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆