![]() ![]() The last part of the controller code would need to be modified as follows: # Notify threads it's time to exit Note that the tutorial's original code would check exitFlag periodically every 1 second, whereas this modified queue requires you to push a dummy object into the queue after setting exitFlag to True - otherwise, the flag will never be checked. The queue's internal locking will ensure that two threads do not interfere for the duration of the call to get(), and no queueLock is needed. Print("%s processing %s" % (threadName, data)) Instead of checking empty() first, just rely directly on the blocking behavior of get(): def process_data(threadName, q): Let me show you how to use the threadsafe queue properly. Without this lock, two threads could enter into the if-statement and both issue a call to get(), meaning that one of them could block, waiting for an item that will never be pushed. The tutorial probably uses the lock to ensure that the thread has exclusive access to the queue from the call to empty() until the call to get(). The issue is that another thread could run in-between the call to empty() and the call to get(), stealing the item that empty() otherwise reported to exist. If empty() returns False it doesn't guarantee that a subsequent call to get() will not block. The reason that locking is needed is hinted at by the documentation for Queue.empty(): ![]() Indeed, this extra lock means that the threadsafe queue in the tutorial could be replaced with an old-fashioned non-threadsafe queue based on a simple list. ![]() In particular, the tutorial is using the threadsafe queue in a way that unfortunately requires an extra lock. I believe the tutorial you're following is a bad example of how to use Python's threadsafe queue. Thread = myThread(threadID, tName, workQueue) Print ("%s processing %s" % (threadName, data)) But in another tutorial, I've seen an example as following: import queue As the official tutorial goes, "The Queue class in this module implements all the required locking semantics". I've been gong through the tutorials about multithreading and queue in python3. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |