Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. import queue
  2. import concurrent
  3. import time
  4. import random
  5. from concurrent import futures
  6. import threading
  7.  
  8. njobs = 20
  9. submission_interval = 0.2
  10. max_work_duration = 3
  11.  
  12. pool = futures.ProcessPoolExecutor(max_workers=3)
  13.  
  14. completed = queue.Queue()
  15.  
  16. def main():
  17.  
  18. # Submit all jobs. They add themselves to "completed"
  19. threading.Thread(target=jobSubmitterThread).start()
  20.  
  21. # Start collecting results while jobs are still being submitted
  22. for i in range(0, njobs):
  23. present = completed.get(timeout=1000)
  24. (tn, passed, work_duration) = present.result()
  25. print ("Job %d took %s seconds and %s" %
  26. (tn, passed, "passed" if passed else "failed"))
  27.  
  28. def jobSubmitterThread():
  29.  
  30. for tn in range(0, njobs):
  31. print("Submitting job number %d" % tn)
  32. future = pool.submit(do_one_job, tn)
  33. future.add_done_callback(lambda f : completed.put(f))
  34. # Demonstrate submission and results collection
  35. # are concurrent
  36. time.sleep(submission_interval)
  37.  
  38. def do_one_job(tn):
  39. pretend_duration = random.randint(0, max_work_duration)
  40. passed = random.randint(0, 1)
  41. # print("Starting job number %d" % tn)
  42. time.sleep(pretend_duration)
  43. return (tn, passed, pretend_duration)
  44.  
  45.  
  46. if __name__ == "__main__":
  47. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement