Guest User

Untitled

a guest
Apr 7th, 2019
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. import time
  2. import threading
  3. from subprocess import check_output
  4. from queue import Queue
  5.  
  6. NUM_THREADS = 10
  7. NUM_JOBS = 20
  8.  
  9. # lock to single-thread printing
  10. print_lock = threading.Lock()
  11.  
  12. # Create the queue and threader
  13. q = Queue()
  14.  
  15. def exampleJob(worker):
  16. """Run the external program, get output and strip leading/trailing whitespace"""
  17.  
  18. # the external program "job.sh" just waits 1 second and echos input parameters
  19. # we must convert the "bytes" output to a string and remove trailing '\n'
  20. result = check_output(['./job.sh', 'hello', 'world']).decode("utf-8").strip()
  21.  
  22. # print the result of the job
  23. # with print_lock:
  24. # print(threading.current_thread().name, worker, result)
  25. # printing without locking seems OK (on MacOS, anyway)
  26. print(threading.current_thread().name, worker, result)
  27.  
  28. def threader():
  29. """Gets a job from the queue and processes it."""
  30.  
  31. while True:
  32. worker = q.get()
  33. exampleJob(worker)
  34. q.task_done()
  35.  
  36. # Start a fixed number of threads
  37. for x in range(NUM_THREADS):
  38. t = threading.Thread(target=threader)
  39. t.daemon = True
  40. t.start()
  41.  
  42. start = time.time()
  43.  
  44. # generate a number of jobs and put them on the queue
  45. # the job is just the "job number"
  46. for worker in range(NUM_JOBS):
  47. q.put(worker)
  48. q.join()
  49.  
  50. # print total elapsed time
  51. delta = time.time() - start
  52. print(f'Took {delta:.2f}s')
Advertisement
Add Comment
Please, Sign In to add comment