Guest User

Untitled

a guest
Nov 17th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. import random
  2. import time
  3. from concurrent.futures import ThreadPoolExecutor, as_completed
  4. from threading import Semaphore
  5. from collections import defaultdict
  6.  
  7.  
  8. def do_task(i):
  9. print("before {i}".format(i=i))
  10. time.sleep(1.05 * random.random())
  11. print("after {i}".format(i=i))
  12. return i
  13.  
  14.  
  15. def with_limitation(sem):
  16. def do(fn, *args, **kwargs):
  17. with sem:
  18. return fn(*args, **kwargs)
  19.  
  20. return do
  21.  
  22.  
  23. sem_map = defaultdict(lambda: Semaphore(2))
  24. xs = ["a", "a", "a", "b", "b", "b", "b", "c"]
  25.  
  26. print("S")
  27. with ThreadPoolExecutor() as ex:
  28. futs = []
  29. for x in xs:
  30. futs.append(ex.submit(with_limitation(sem_map[x]), do_task, x))
  31. for f in as_completed(futs):
  32. print("ok", f.result())
  33. print("E")
Add Comment
Please, Sign In to add comment