mutate_instance.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # test concurrent mutating access to a shared user instance
  2. #
  3. # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
  4. import _thread
  5. # the shared user class and instance
  6. class User:
  7. def __init__(self):
  8. self.a = 'A'
  9. self.b = 'B'
  10. self.c = 'C'
  11. user = User()
  12. # main thread function
  13. def th(n, lo, hi):
  14. for repeat in range(n):
  15. for i in range(lo, hi):
  16. setattr(user, 'attr_%u' % i, repeat + i)
  17. assert getattr(user, 'attr_%u' % i) == repeat + i
  18. with lock:
  19. global n_finished
  20. n_finished += 1
  21. lock = _thread.allocate_lock()
  22. n_repeat = 30
  23. n_range = 50 # 300 for stressful test (uses more heap)
  24. n_thread = 4
  25. n_finished = 0
  26. # spawn threads
  27. for i in range(n_thread):
  28. _thread.start_new_thread(th, (n_repeat, i * n_range, (i + 1) * n_range))
  29. # busy wait for threads to finish
  30. while n_finished < n_thread:
  31. pass
  32. # check user instance has correct contents
  33. print(user.a, user.b, user.c)
  34. for i in range(n_thread * n_range):
  35. assert getattr(user, 'attr_%u' % i) == n_repeat - 1 + i