fork(2) download
  1. #!/usr/bin/env python3
  2. import threading
  3. import time
  4. from concurrent.futures import ThreadPoolExecutor as Pool
  5. from timeit import default_timer as timer
  6.  
  7. def do_work(item):
  8. time.sleep(.1) # pretend to do some lengthy work.
  9. return threading.current_thread().name, item # return results
  10.  
  11. with Pool(max_workers=4) as executor:
  12. # submit work items to executor (in this case, just a number).
  13. start = timer()
  14. for name, item in executor.map(do_work, range(20)):
  15. print("%s %s" % (name, item)) # print results
  16.  
  17. # "Work" took .1 seconds per task.
  18. # 20 tasks serially would be 2 seconds.
  19. # With 4 threads should be about .5 seconds
  20. print('time:', timer() - start)
  21.  
Success #stdin #stdout 0.23s 44528KB
stdin
Standard input is empty
stdout
Thread-1 0
Thread-2 1
Thread-3 2
Thread-4 3
Thread-1 4
Thread-2 5
Thread-3 6
Thread-4 7
Thread-1 8
Thread-2 9
Thread-3 10
Thread-4 11
Thread-1 12
Thread-2 13
Thread-3 14
Thread-4 15
Thread-2 16
Thread-1 17
Thread-3 18
Thread-4 19
time: 0.5035951137542725