Advertisement
renix1

Threading, acquire and lock with search

Feb 26th, 2017
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. import threading
  2. import queue
  3. import os
  4.  
  5.  
  6. class SearchFiles(threading.Thread):
  7.     def __init__(self, q):
  8.         self.lock = threading.Lock()
  9.         self.files = []
  10.  
  11.     def run(self):
  12.         path = q.get()
  13.         if os.path.exists(path):
  14.             print("Searching...")
  15.             for root, dirs, files in os.walk(path):
  16.                 for f in files:
  17.                     q.put(os.path.join(root, f))
  18.                     self.lock.acquire()
  19.                     self.append()
  20.                     self.lock.release()
  21.             else:
  22.                 files = self.result()
  23.                 tam = len(files)
  24.                 for f in files:
  25.                     print(f)
  26.                 print("%d files" % tam)
  27.  
  28.     def append(self):
  29.         self.files.append(q.get())
  30.  
  31.     def result(self):
  32.         return self.files
  33.  
  34. if __name__ == '__main__':
  35.     q = queue.Queue()
  36.     q.put("C:\\Windows")
  37.     files = SearchFiles(q)
  38.     files.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement