c++ - c++进入临界区和上下文切换

标签 c++ multithreading winapi critical-section context-switching

刚接触线程编程(目前在公司项目中需要用到win32和c++),想请问进入临界区是不是就意味着不进行上下文切换?这是否意味着线程将锁定资源直到它离开临界区?

此外,我目前正在阅读“Win32 中的多线程应用程序”一书,这本书看起来不错,但是有没有更好读和更新的书供新手学习 win32 中的线程?

非常感谢^_^

最佳答案

你只是一个用户模式进程,你不能阻止操作系统上下文切换到另一个进程。这意味着在第一个线程离开之前,您的进程中的其他线程都不能进入临界区。

来自 MSDN (强调我的):

A thread uses the EnterCriticalSection or TryEnterCriticalSection function to request ownership of a critical section. It uses the LeaveCriticalSection function to release ownership of a critical section. If the critical section object is currently owned by another thread, EnterCriticalSection waits indefinitely for ownership.

再一次,EnterCriticalSection说:

Waits for ownership of the specified critical section object. The function returns when the calling thread is granted ownership.

回答“这是否会阻止线程之间的上下文切换”的问题。不,不是真的。假设您有两个线程,ABA 调用 EnterCriticalSection 并进入 CS。当他在 CS 中使用共享资源时,操作系统仍然可以上下文切换到线程 BB 将像以前一样继续运行,直到他到达 EnterCriticalSection 调用,此时他将阻塞。

现在这个阻塞是如何真正实现取决于 Windows 的。但最有可能的是,而不是“旋转”(我可以进入吗?不。现在?不。现在?不。)操作系统会将那个线程放在“阻塞”队列中,并且直到他正在等待的东西才安排线程( CS)可用。届时,他将被安排,对 EnterCriticalSection 的调用将成功。

另见

关于c++ - c++进入临界区和上下文切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19559042/

相关文章:

c++ - C++中是否有任何常量可用作比较中的最小值/最大值

java - 只让一个正在运行的线程执行一个 catch block ?

python - 如何在python中同步线程?

c++ - 自定义绘制 ListView 的问题

C++ COM、Direct2D、Win32 和 WM_CLOSE

c++ - 具有 boolean 值的奇怪行为

c++ - 语法错误 : Identifier 'string' error C2061

c++ - 使用 C++ Hook QT 应用程序以捕获应用程序的文本名称

java - 清理线程池的问题

c++ - 如何要求重新启动 firefox?