I'm currently working on a project that gets social network notification data from Facebook, Twitter and GMail. When a notification is received, a serial signal is sent to an Arduino UNO, which flashes an LED that corresponds to that social network.
For optimal speed, I have decided to use multithreading, through the threading module. What I would like to know is whether or not I need to use threading.Lock() and create a lock. Over IRC, KermM gave me some advice:
The code is seperated into a series of classes. SocialLights governs the serial connection to the Arduino.
Code:
Thus far, I have written two social network monitoring classes, one for GMail and the other for Twitter. They both follow this sort of format.
Code:
I have heavily condensed this code, but it looks roughly like this.
In the main body of code, each class is instantiated, and is attached to a SocialLights object which is also instantiated.
Code:
Should I be using threading.Lock() and using the acquire() and release() methods?
For optimal speed, I have decided to use multithreading, through the threading module. What I would like to know is whether or not I need to use threading.Lock() and create a lock. Over IRC, KermM gave me some advice:
KermM wrote:
If you have data structures shared between threads, you should only access them when you hold a lock on them
The code is seperated into a series of classes. SocialLights governs the serial connection to the Arduino.
Code:
class SocialLights(object):
def __init__(self, serial_port, baud_rate):
# SERIAL CONNECTION STUFF HERE...
def notify(self, icon):
"""Causes the specified icon to fade"""
self._icon = icon
if self._icon == "twitter":
self._ser.write("t")
elif self._icon == "facebook":
self._ser.write("f")
elif self._icon == "gmail":
self._ser.write("g")
def clear(self):
"""Turns all LEDs off"""
self._ser.write("c")
Thus far, I have written two social network monitoring classes, one for GMail and the other for Twitter. They both follow this sort of format.
Code:
class GMailReader(threading.Thread):
def __init__(self, username, password, lights):
# AUTHENTICATION STUFF...
self.__lights = lights
def run(self):
if notification:
self.__lights.notify("gmail")
I have heavily condensed this code, but it looks roughly like this.
In the main body of code, each class is instantiated, and is attached to a SocialLights object which is also instantiated.
Code:
sl = SocialLights("/dev/ttyACM1", 9600)
sl.clear()
# Instantiate the social network classes and attatch them to 'sl'
tr = socialnetworks.TwitterReader(API_KEY, API_SECRET, ACCESS_KEY,
ACCESS_SECRET, sl)
gr = socialnetworks.GMailReader(GMAIL_USERNAME, GMAIL_PWD, sl)
# Run the threads:
tr.start()
gr.start()
Should I be using threading.Lock() and using the acquire() and release() methods?