From ea27801577735bed44edd42fe47bff28fb059320 Mon Sep 17 00:00:00 2001 From: Brandon Rozek Date: Wed, 6 May 2020 23:06:13 -0400 Subject: [PATCH] New Post --- content/blog/pyseamlessvarlock.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 content/blog/pyseamlessvarlock.md diff --git a/content/blog/pyseamlessvarlock.md b/content/blog/pyseamlessvarlock.md new file mode 100644 index 0000000..d649c4f --- /dev/null +++ b/content/blog/pyseamlessvarlock.md @@ -0,0 +1,28 @@ +--- +title: "Quick Python: Seamless Variable Locks" +date: 2020-05-06T23:01:39-04:00 +draft: false +tags: ["python", "concurrency"] +--- + +Combining Python's [Getters and Setters](https://brandonrozek.com/blog/pygetset/) with locks can give us seamless thread-safe variable access. + +```python +from threading import Lock +class Person: + def __init__(self): + self._age = 0 + self.age_lock = Lock() + @property + def age(self): + a = None + with self.age_lock: + a = self._age + return a + + @age.setter + def age(self, a): + with self.age_lock: + self._age = a +``` +