thread_gc1.py 841 B

12345678910111213141516171819202122232425262728293031323334
  1. # test that we can run the garbage collector within threads
  2. #
  3. # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
  4. import gc
  5. import _thread
  6. def thread_entry(n):
  7. # allocate a bytearray and fill it
  8. data = bytearray(i for i in range(256))
  9. # do some work and call gc.collect() a few times
  10. for i in range(n):
  11. for i in range(len(data)):
  12. data[i] = data[i]
  13. gc.collect()
  14. # print whether the data remains intact and indicate we are finished
  15. with lock:
  16. print(list(data) == list(range(256)))
  17. global n_finished
  18. n_finished += 1
  19. lock = _thread.allocate_lock()
  20. n_thread = 4
  21. n_finished = 0
  22. # spawn threads
  23. for i in range(n_thread):
  24. _thread.start_new_thread(thread_entry, (10,))
  25. # busy wait for threads to finish
  26. while n_finished < n_thread:
  27. pass