gpt4 book ai didi

multithreading - 线程通常应何时产生?

转载 作者:行者123 更新时间:2023-12-04 08:27:03 25 4
gpt4 key购买 nike

在大多数语言/框架中,存在一种让线程对其他线程产生控制权的方法。但是,我真的想不起来从某个线程获得 yield 是解决给定问题的正确解决方案的时候。通常,何时应使用Thread.yield()sleep(0)等?

最佳答案

一种用例可能是测试并发程序,尝试找到揭示同步模式中缺陷的交错。例如在Java中:

A useful trick for increasing the number of interleavings, and therefore more effectively exploring the state space of your programs, is to use Thread.yield to encourage more context switches during operations that access shared state. (The effectiveness of this technique is platform-specific, since the JVM is free to treat THRead.yield as a no-op [JLS 17.9]; using a short but nonzero sleep would be slower but more reliable.) — JCIP



从Java的角度来看,另一个有趣的地方是它们的语义未定义:

The semantics of Thread.yield (and Thread.sleep(0)) are undefined [JLS 17.9]; the JVM is free to implement them as no-ops or treat them as scheduling hints. In particular, they are not required to have the semantics of sleep(0) on Unix systemsput the current thread at the end of the run queue for that priority, yielding to other threads of the same prioritythough some JVMs implement yield in this way. — JCIP



当然,这使它们不可靠。这是非常特定于Java的,但是,总的来说,我相信以下是正确的:

两者都是低级机制,可用于影响 调度顺序。如果使用它来实现某些功能,则此功能基于OS调度程序的可能性,这似乎是一个很糟糕的主意。这应该由更高级别的同步结构来管理。

对于测试目的或将程序强制进入某种状态,它似乎是一个方便的工具。

关于multithreading - 线程通常应何时产生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14654532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com