Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your vendor would be right if yours was <strong>pure python</strong> code; however, C extensions may release the <a href="http://effbot.org/pyfaq/what-is-the-global-interpreter-lock.htm" rel="nofollow noreferrer">GIL</a>, and therefore allows for actual multithreading.</p> <p>In particular, time.sleep <strong>does</strong> release the GIL (you can check it directly from the source code, <a href="http://svn.python.org/view/python/trunk/Modules/timemodule.c?view=markup" rel="nofollow noreferrer">here</a> - look at <code>floatsleep</code> implementation); so your code should not have any problem. As a further proof, I have made also a simple test, just removing the calls to USB, and it actually works as expected:</p> <pre><code>from threading import Thread import time import sys usb_device = 0 def usb_dump(): for i in range(100): time.sleep(0.001) print "dumping usb" class DumpThread(Thread): def run(self): usb_dump() t = DumpThread() t.start() print "Sleep 1" time.sleep(1) print "End" sys.exit(0) </code></pre> <p>Finally, just a couple of notes on the code you posted:</p> <ul> <li>usb_device is not being passed to the thread. You need to pass it as a parameter or (argh!) tell the thread to get it from the global namespace.</li> <li>Instead of forcing sys.exit(), it could be better to just signal the thread to stop, and then closing USB device. I suspect your code could get some multithreading issue, as it is now.</li> <li>If you need just a periodic poll, threading.Timer class may be a better solution for you.</li> </ul> <p>[<em>Update</em>] About the latest point: as told in the comment, I think a <code>Timer</code> would better fit the semantic of your function (a periodic poll) and would automatically avoid issues with the GIL not being released by the vendor code.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload