mutate_list.py 929 B

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