请从Linux、Windows的角度解释一下?
我正在使用 C# 编程,这两个术语会有所不同吗?请尽可能多地发布,并附上示例等......
谢谢
最佳答案
对于 Windows,临界区比互斥锁更轻。
互斥锁可以在进程之间共享,但总是会导致对内核的系统调用有一些开销。
关键部分只能在一个进程中使用,但其优点是它们仅在争用情况下才切换到内核模式 - 非竞争获取,这应该是常见的情况,速度非常快。在争用的情况下,它们进入内核等待某个同步原语(如事件或信号量)。
我编写了一个快速示例应用程序,用于比较两者之间的时间。在我的系统上进行 1,000,000 次无竞争的获取和释放,互斥量需要一秒钟。 1,000,000 次获取的关键部分大约需要 50 毫秒。
这是测试代码,如果 mutex 是第一个或第二个,我运行它并得到类似的结果,所以我们没有看到任何其他效果。
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);
https://stackoverflow.com/questions/800383/