mutate_set.py 760 B

12345678910111213141516171819202122232425262728293031323334353637
  1. # test concurrent mutating access to a shared set object
  2. #
  3. # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
  4. import _thread
  5. # the shared set
  6. se = set([-1, -2, -3, -4])
  7. # main thread function
  8. def th(n, lo, hi):
  9. for repeat in range(n):
  10. for i in range(lo, hi):
  11. se.add(i)
  12. assert i in se
  13. se.remove(i)
  14. assert i not in se
  15. with lock:
  16. global n_finished
  17. n_finished += 1
  18. lock = _thread.allocate_lock()
  19. n_thread = 4
  20. n_finished = 0
  21. # spawn threads
  22. for i in range(n_thread):
  23. _thread.start_new_thread(th, (50, i * 500, (i + 1) * 500))
  24. # busy wait for threads to finish
  25. while n_finished < n_thread:
  26. pass
  27. # check set has correct contents
  28. print(sorted(se))