~/talk

Implementing a decorator for thread synchronisation

Talkat PyCon APAC 2018 · 2018-05-31..06-02· [python, concurrency]
slides:none on file

Shows how to implement Java-style synchronized in Python by building a decorator that locks per-instance, per-class or per-function, using wrapt to handle method binding and preserve introspection, and relying on setdefault atomic to create per-instance locks safely; supports using the decorator as a context manager too; reproduces the race where 100 threads expected 100 increments but got ~11 and explains why naive decorators and monkey-patching break in corner cases.

AI-written summary · about

  1. 0:00Start
  2. 0:42Parallel execution using threads
  3. 2:27Manipulating a counter value
  4. 3:49Synchronisation using a lock
  5. 4:51Synchronisation in Java
  6. 5:37Can we achieve this in Python?
  7. 7:39Requires lock be a class attribute
  8. 8:53Store lock as an instance attribute
  9. 12:05Lock is automatically created
  10. 12:17Only works for instance methods
  11. 12:36Switch to the wrapt decorator package
  12. 13:41Implementing a universal decorator
  13. 15:09Rewrite decorator using wrapt
  14. 16:41Works on normal function
  15. 17:09What about static methods?
  16. 17:31And class methods?
  17. 18:10Extra trickery required
  18. 19:48Test class method again
  19. 20:00Verify no lock on class method Fails as expected
  20. 20:19Verify separate locks for instance and class
  21. 20:54Locking based on context used
  22. 21:40Locking on code blocks in Java
  23. 21:50Could we also do this?
  24. 22:01Type created by a decorator
  25. 22:28What the decorator did
  26. 22:53Rewrite to use function wrapper class
  27. 23:44Extend to be a context manager
  28. 24:26Synchronise across instance methods
  29. 25:02Synchronise access to class attributes
  30. 25:41Explicitly sharing a lock
  31. 26:09Detecting a resource lock Detect when lock object has been passed
  32. 27:00What about context manager?
  33. 28:40Reuse, don't reimplement
  34. 29:29Don't write decorators from scratch either
~/search
type to search 6,249 conferences, 138,987 speakers and 185,172 talks
~/help
cmdctrl k
search every conference, speaker and series
/
focus the filter search
h
home
c
conferences
s
speakers
e
series
t
light / dark — the status bar button does the same
?
this help
esc
close this, then clear every filter — or just the search, while you are typing in it

Ignored while you are typing. Pages without a filter rail have no search to focus.