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

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

提交回复
热议问题