]> Repositories - Adafruit_Blinka-hackapet.git/commitdiff
Add a lock for thread safety when the I2C class is used in a with statement
authorHamish McIntyre-Bhatty <hamishmb@live.co.uk>
Thu, 31 Oct 2019 14:38:40 +0000 (14:38 +0000)
committerHamish McIntyre-Bhatty <hamishmb@live.co.uk>
Thu, 31 Oct 2019 14:38:40 +0000 (14:38 +0000)
src/busio.py

index 9702848a841246889af28d575e41db6baa51861a..73c88ef6d57c0f6708f778f2bd8ae281c6d73549 100755 (executable)
@@ -7,6 +7,8 @@ See `CircuitPython:busio` in CircuitPython for more details.
 * Author(s): cefn
 """
 
 * Author(s): cefn
 """
 
+import threading
+
 from adafruit_blinka import Enum, Lockable, agnostic
 from adafruit_blinka.agnostic import board_id, detector
 import adafruit_platformdetect.board as ap_board
 from adafruit_blinka import Enum, Lockable, agnostic
 from adafruit_blinka.agnostic import board_id, detector
 import adafruit_platformdetect.board as ap_board
@@ -35,6 +37,8 @@ class I2C(Lockable):
                 "No Hardware I2C on (scl,sda)={}\nValid I2C ports: {}".format((scl, sda), i2cPorts)
             )
 
                 "No Hardware I2C on (scl,sda)={}\nValid I2C ports: {}".format((scl, sda), i2cPorts)
             )
 
+        self._lock = threading.RLock()
+
     def deinit(self):
         try:
             del self._i2c
     def deinit(self):
         try:
             del self._i2c
@@ -42,9 +46,11 @@ class I2C(Lockable):
             pass
 
     def __enter__(self):
             pass
 
     def __enter__(self):
+        self._lock.acquire()
         return self
 
     def __exit__(self, exc_type, exc_value, traceback):
         return self
 
     def __exit__(self, exc_type, exc_value, traceback):
+        self._lock.release()
         self.deinit()
 
     def scan(self):
         self.deinit()
 
     def scan(self):