线程通常应何时产生? [英] When should a thread generally yield?

查看:93
本文介绍了线程通常应何时产生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In most languages/frameworks, there exists a way for a thread to yield control to other threads. However, I can't really think of a time when yielding from a thread was the correct solution to a given problem. When, in general, should one use Thread.yield(), sleep(0), etc?

推荐答案

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

One use case could be for testing concurrent programs, try to find interleavings that reveal flaws in your synchronization patterns. For instance in Java:

增加交织次数的有用技巧,以及 因此,可以更有效地探索程序的状态空间, 是要使用Thread.yield鼓励在操作期间进行更多上下文切换 访问共享状态的操作. (此的有效性 该技术是特定于平台的,因为JVM是免费的 THRead.yield为空操作[JLS 17.9];使用短暂但非零的睡眠 会更慢,但更可靠.)— JCIP

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的角度来看,有趣的是它们的语义没有定义:

Also interesting from the Java point of view is that their semantics are not defined:

Thread.yield(和Thread.sleep(0))的语义未定义 [JLS 17.9]; JVM可以自由地将它们实现为无操作或对待它们 作为计划提示.特别是,它们不需要具有 Unix系统上sleep(0)的语义放在当前线程的末尾 该优先级的运行队列的数量,从而屈服于 相同的优先级,尽管某些JVM以这种方式实现收益. — JCIP

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的,但是总的来说,我相信以下是正确的:

This makes them, of course, rather unreliable. This is very Java specific, however, in generally I believe following is true:

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

Both are low-level mechanism which can be used to influence the scheduling order. If this is used to achieve a certain functionality then this functionality is based on the probability of the OS scheduler which seems a rather bad idea. This should be managed by higher-level synchronization constructs instead.

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

For testing purpose or for forcing the program into a certain state it seems a handy tool.

这篇关于线程通常应何时产生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆