In there something similar to Java's Thread.yield() in Python? Does that even make sense?

后端 未结 3 1705
广开言路
广开言路 2021-02-15 13:24

I want to tell my Python threads to yield, and so avoid hogging the CPU unnecessarily. In Java, you could do that using the Thread.yield() function. I don\'t think

3条回答
  •  爱一瞬间的悲伤
    2021-02-15 13:33

    Thread.yield() is missing from python because perhaps it has been forgotten, or the designer thought that all synchronization and interprocess communication issues are solvable without Thread.yield().

    I'd use Thread.yield() for the following issue:

    E.g. there is a job queue and there are 2 worker threads which can fetch entries from the job queue and place entries into the job queue. One way to solve it is to use the threading.Condition class. When worker 'B' wants to fetch a queue entry, but the queue is empty, it goes to wait state (Condition.wait()). When worker 'A' places entry into the queue, it wakes up worker 'B' (Condition.notify()). At this point yielding is essential, because if worker 'A' doesn't yield here, worker 'A' can fetch the task before the woken up worker 'B' which causes race condition issue.

    I wonder how it is solvable without Thread.yield().

提交回复
热议问题