mutate_bytearray.py 1013 B

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