windows - 互斥锁和临界区有什么区别?

请从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/

相关文章:

python - 修改刻度标签文本

python - 如何保持 Python 脚本输出窗口打开?

python - 如何在 Python 中获取已排序数组的索引

python - 使用代码存储库时如何引用资源的相对路径

c - GCC 的 __builtin_expect 在 if else 语句中的优势是什么?

linux - 获取图像尺寸(不是文件大小)的快速方法

python - 不可变与可变类型

linux - 如何从远程 SSH session 将数据发送到本地剪贴板

python - 在 Python 中清除终端

linux - 如何使 rpm 自动安装依赖项