Reputation: 1295
I have a script that read data from Serial Port, so I have an infinite loop that always fill my data to global variable, and also I schedule a function that run every X seconds to post in the database, and this function also use the same global variable.
Here's a small example I create it to show you my situation :
import serial
import schedule
import threading
shared_var = []
def save_to_db():
print(threading.current_thread())
global shared_var
for l in shared_var:
print(l)
shared_var.clear()
def run_threaded(job_func):
job_thread = threading.Thread(target=job_func)
job_thread.start()
ser = serial.Serial() # initialize the serial
ser.baudrate = 115200 # set the baud rate : default 115200
ser.port = "/dev/ttyUSB0" # set the port to use
ser.timeout = 30
ser.write_timeout = None
if not ser.is_open:
ser.open() # Open port
ser.write(b'scan=01\r\n') # Stop scan if already started
schedule.every(5).seconds.do(run_threaded, save_to_db)
while 1:
schedule.run_pending()
line = ser.readline()
shared_var.append(line)
print(threading.current_thread())
Is this code can cause a problem ? more specific what will happen if the MainThread (the one that read from Serail Port and write to shared_var
) write to the shared variable between the 2 thread and in the same moment the other Thread read from the variable, is This will cause a problem because the 2 threads gonna access the same global variable in the same time ? and if yes It's a problem should I use mutex mechanism for that ?
Upvotes: 1
Views: 72
Reputation: 466
Yes it is sure that you will have a problem if 2 processes affect the same variable at the same time.
To overcome this you must use threading.Lock() (this is Threading's mutex system).
lock = threading.Lock()
lock.acquire()
try:
yourVariable += 1
finally:
lock.release()
I hope I helped you.
Upvotes: 1