刚接触线程编程(目前在公司项目中需要用到win32和c++),想请问进入临界区是不是就意味着不进行上下文切换?这是否意味着线程将锁定资源直到它离开临界区?
此外,我目前正在阅读“Win32 中的多线程应用程序”一书,这本书看起来不错,但是有没有更好读和更新的书供新手学习 win32 中的线程?
非常感谢^_^
最佳答案
你只是一个用户模式进程,你不能阻止操作系统上下文切换到另一个进程。这意味着在第一个线程离开之前,您的进程中的其他线程都不能进入临界区。
来自 MSDN (强调我的):
A thread uses the
EnterCriticalSection
orTryEnterCriticalSection
function to request ownership of a critical section. It uses theLeaveCriticalSection
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.
回答“这是否会阻止线程之间的上下文切换”的问题。不,不是真的。假设您有两个线程,A 和 B。 A 调用 EnterCriticalSection
并进入 CS。当他在 CS 中使用共享资源时,操作系统仍然可以上下文切换到线程 B。 B 将像以前一样继续运行,直到他到达 EnterCriticalSection
调用,此时他将阻塞。
现在这个阻塞是如何真正实现取决于 Windows 的。但最有可能的是,而不是“旋转”(我可以进入吗?不。现在?不。现在?不。)操作系统会将那个线程放在“阻塞”队列中,并且直到他正在等待的东西才安排线程( CS)可用。届时,他将被安排,对 EnterCriticalSection
的调用将成功。
另见
关于c++ - c++进入临界区和上下文切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19559042/