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

后端 未结 3 1712
广开言路
广开言路 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().

    0 讨论(0)
  • 2021-02-15 13:46

    Dup of: How does a threading.Thread yield the rest of its quantum in Python?.

    time.sleep(0)
    
    0 讨论(0)
  • 2021-02-15 13:53

    The interpreter will switch from one thread to another periodically anyway without your intervention - you don't need to tell the system not to 'hog' a thread.

    However, under normal circumstances, only one Python thread is executing at any one time. (Exceptions tend to revolve around times when threads are waiting on input from external devices such as the hard disk or the network.) This is due to the Global Interpreter Lock. This does mean however that you probably aren't getting as much benefit from threads in Python as you would in Java or many other languages. Getting around this problem is not necessarily trivial, although moving to multiprocessing instead of multithreading is one good approach, if possible.

    However, what you want to do seems flawed in some sense - if you have 2 threads and they both have work to do, you shouldn't have to write application-side code to switch between them. That's the job of the operating system or the virtual machine. If you find yourself telling one thread to 'do less' because you want to favour another thread in terms of processor time, then rather than adding arbitrary yielding or sleeping, you should probably be setting thread priorities instead. (Although again, this may not have much meaning in Python given the presence of the Global Interpreter Lock.)

    0 讨论(0)
提交回复
热议问题