![]() ![]() When the worker thread is created, it is given a reference to one queue for input, and one queue for output. In Python 3 this was fixed and the module is named in lowercase - queue). This is best done with the help of Queue objects from the Queue module (yep, it's Queue.Queue - a bit awkward, I agree. Second, passing data into and out of a thread. Keep in mind that the join method is called in the context of the main thread, while the body of the run method is executed in the context of the worker thread. You can think of threading.Event as a synchronized boolean flag. The main loop in the thread's run method checks this flag, and exits when it's set. The join method of Thread is overridden, and before calling the actual join of the parent class, it "sets" the self.stoprequest attribute, which is a threading.Event. This is accomplished by politely asking the thread to die. Let's address the two issues mentioned at the top of the post.įirst, killing a thread. For folks with less experience, I will elaborate. """ for path, dirs, files in os.walk(dirname):įor experienced programmers, going over the code and its documentation and comments should be enough. """ Given a directory name, yields the names of all files (not dirs) contained in this directory and its sub-directories. Self.result_q.put(( self.name, dirname, filenames)) while not ():įilenames = list( self._files_in_dir(dirname)) ![]() # Also, 'get' is given a timeout, so stoprequest is always checked, # even if there's nothing in the queue. The tasks are taken with a blocking 'get', so no CPU # cycles are wasted while waiting. # As long as we weren't asked to stop, try to take new tasks from the # queue. Ask the thread to stop by calling its join() method. Output is done by placing tuples into the Queue passed in result_q. Input is done by placing directory names (as strings) into the Queue passed in dir_q. """ A worker thread that takes directory names from a queue, finds all files in them recursively and reports the result. Import os, time import threading, Queue class WorkerThread(threading.Thread): ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |