0

I'm trying to implement a python script that can send serial data generated by two different threads. Now I was able to set the threads running, I would like to create a shared memory with semaphores between the manager process and the sub threads. The code of the manager is the following

import DetectorService
import HearingService


if __name__=='__main__':
    global shm01
    t1 = Thread(target = DetectorService.start)
    t2 = Thread(target = HearingService.start)
    t1.setDaemon(True)
    t2.setDaemon(True)
    t1.start()
    t2.start()
    while True:
        # Get data from thread01
        # Get data from thread02
        # Send data via serial port
        pass

Then there is a minimal representation of a thread:

import time

def start():
    while True:
        a = a + 1
        time.sleep(0.5)

For instance, my goal is to access the a variable and send the value through the serial port. The serial communication is not a problem, I know how to do it.

So my question is, how can I implement the shared memory?

  • 1
    Why not using a queue to exchange data between the threads? https://docs.python.org/3/library/queue.html – Merk Feb 20 '22 at 10:59

1 Answers1

0

There are various ways to implement this. One simple way to serialize the access to a shared resource (which will make the access safe) is by using a Lock. You can read more here.

As an example, your threads might collect the data that needs to be sent in a shared list, like this:

data_to_send = []

and when you need to read from or write to that list, simply do so in the context of a global Lock object. Like this:

with lock:
    data_to_send.append(some_data)
at54321
  • 8,726
  • 26
  • 46
  • Python lists are already thread-safe, so there is no need for a lock here AFAIK. – Mark Setchell Feb 20 '22 at 11:19
  • If you *only* append data to a list, yes. But in OP's case they will need to do other stuff as well, like reading that data, keeping track of what's sent, what's being processed, etc. In theory they might be able to get away with no explicit locking, but that cannot be said without going over the complete solution. – at54321 Feb 20 '22 at 11:30