临界区

发布于 2024-08-12 04:08:40 字数 252 浏览 5 评论 0原文

我对某事不确定。

例如,当我在 C++ 中使用 critical_section/mutex/semaphor 时,如何防止 busy_wait 问题?

我的意思是,当一个线程到达临界区并且该临界区被其他线程占用时,什么可以防止该线程浪费循环时间并且什么也不等待?

例如, 我应该调用 TryEnterCriticalSection 并检查线程是否获得所有权,否则调用 sleep(0) 吗?

我有点困惑

谢谢

i'm not sure about something.

when i use critical_section/mutex/semaphor in c++ for example , how does the busy_wait problem being prevented ?

what i mean is when a thread reaches a critical section and the critical section is occupied by other thread, what prevents the thread from wasting cycle time and wait for nothing ?

for example,
should i call TryEnterCriticalSection and check if the thread obtained ownership and otherwise call sleep(0) ?

i'm a bit perplexed

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

云醉月微眠 2024-08-19 04:08:40

这是 Windows 特有的,但 Linux 也类似。

Windows 有线程就绪队列的概念。这些线程已准备好运行,并将在某个时刻在可用处理器上运行。选择立即运行哪些线程有点复杂 - 线程可以具有不同的优先级,它们的优先级可以临时提高,等等。

当线程等待同步原语(如 CRITICAL_SECTION 或互斥体)时,它不会被放置在就绪队列中 - Windows 甚至不会尝试运行该线程,并且会在可能的情况下运行其他线程。在某些时候,线程将被移回就绪队列,例如当拥有 CS 或互斥体的线程释放它时。

This is Windows specific, but Linux will be similar.

Windows has the concept of a ready queue of threads. These are threads that are ready to run, and will be run at some point on an available processor. Which threads are selected to run immediately is a bit complicated - threads can have different priorities, their priorities can be temporarily boosted, etc.

When a thread waits on a synchronization primitive like a CRITICAL_SECTION or mutex, it is not placed on the ready queue - Windows will not even attempt to run the thread and will run other threads if possible. At some point the thread will be moved back to the ready queue, for instance when the thread owning the CS or mutex releases it.

攒眉千度 2024-08-19 04:08:40

该线程不会占用任何系统资源,因为它将被标记为“等待”。一旦占用临界区的线程完成,它就会发出一个信号,将等待线程移动到就绪队列。

The thread is not going to be taking any system resources, because it will be marked as "waiting". As soon as the thread occupying the critical region finishes, it will send out a signal that will move the waiting thread to the ready queue.

冧九 2024-08-19 04:08:40

这些控制结构允许无法进入的线程休眠,直到临界区中完成执行的线程生成中断,从而阻止无法进入的线程进行繁忙等待。因为线程处于睡眠状态,所以它没有使用处理器周期,因此没有 busy_wait。

These control structures stop the thread that can't enter from doing a busy wait by allowing it to sleep until an interrupt is generated by the thread that is in the critical section finishing execution. Because the thread is asleep it is not using processor cycles, so no busy_wait.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文