thread_lock1.py 918 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # test _thread lock object using a single thread
  2. #
  3. # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
  4. import _thread
  5. # create lock
  6. lock = _thread.allocate_lock()
  7. print(type(lock) == _thread.LockType)
  8. # should be unlocked
  9. print(lock.locked())
  10. # basic acquire and release
  11. print(lock.acquire())
  12. print(lock.locked())
  13. lock.release()
  14. print(lock.locked())
  15. # try acquire twice (second should fail)
  16. print(lock.acquire())
  17. print(lock.locked())
  18. print(lock.acquire(0))
  19. print(lock.locked())
  20. lock.release()
  21. print(lock.locked())
  22. # test with capabilities of lock
  23. with lock:
  24. print(lock.locked())
  25. # test that lock is unlocked if an error is rasied
  26. try:
  27. with lock:
  28. print(lock.locked())
  29. raise KeyError
  30. except KeyError:
  31. print('KeyError')
  32. print(lock.locked())
  33. # test that we can't release an unlocked lock
  34. try:
  35. lock.release()
  36. except RuntimeError:
  37. print('RuntimeError')