How do I do time.sleep in certain thread in Python?

Is the overhead for thread switching in Python greater than for C/C++ threads?

Dmitry Chechik at Quora Visit the source

Was this solution helpful to you?

Other answers

For the most part, threads in the C Python implementation must obtain a lock on the interpreter to start executing bytecode. So I'd expect that Python threads have a strictly greater context switch time than the userspace threads on which they are based.

Henry Robinson

CPython uses native OS threads when you create new threads using the threading module. Every thread you make maps cleanly to a native thread. However, as the talk in Dmitry's post points out, Python will end up competing with the OS a great deal, and this competition makes thread switching in Python expensive, especially in some pathological cases involving fun things like signal handling (although some recent patches have fixed some of these issues). Essentially what happens is that the OS's scheduler may want to run a thread, but even if the OS schedules a thread, it doesn't mean that CPython GIL itself has "unlocked" the thread. The thread can sit around doing nothing until the OS either schedules a different thread, or until Python happens to unlock the same thread. The full story is pretty complicated ; look at http://blip.tv/file/2232410 . This is a classic case of the Law of Leaky Abstractions ( http://www.joelonsoftware.com/articles/LeakyAbstractions.html ). You also see this with network protocols a lot (layers and layers and layers of windows/segments/fragmentation modes/retry modes == incredible inefficiency).

Vaibhav Mallya

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.