Monitor two(2) serial ports at the same time asynchronously in Python
Question: I have two serial ports feeding data into Python. One is feeding GPS strings
(about 4 lines per second) and the other feeding data strings from a gas
monitor (about 1 line every second)

I would like to monitor both gps and gas feeds at the same time and combine
the data in realtime. I only need to receive data frpm the serial ports.

My problem is that I can't seem to figure out how to get both python functions
running at the same time.

I have the threading module and the multiprocessing module installed with
Python 2.7.

Any ideas on a good way to combine serial info? This is my third Python
program ever so please be gentle with me :-)

here's the code:

    
    
    import threading
    import multiprocessing
    
    def readGas():
        global GAScount
        global GASline
        while GAScount<15:
            GASline = gas.readline()
            GasString = GASline.startswith('$')
            if GasString is True:
                print GASline
            GAScount = GAScount+1
    
    def readGPS():
        global GPScount
        global GPSline
        while GPScount<50:
            GPSline = gps.readline()
            GPSstring = GPSline.startswith('$')
            if GPSstring is True:
                print GPSline
            GPScount = GPScount+1
    
    openGPS()
    openGas()
    


Answer: I think threads would be a good choice in your case, as you don't expect very
high frequencies. It will be much simpler than multiprocessing, because the
memory remains shared between threads and you have less to worry. The only
remaining issue is that your acquisitions won't be exactly at the same time
but rather one right after the other. If you really need synchronized data,
you need to go with multiprocessing.

for threading :

    
    
    import threading
    
    # create your threads:
    gps = threading.Thread(target=openGPS)
    gas=threading.Thread(target=openGas)
    
    #start your threads:
    gps.start()
    gas.start()
    

And you now have 2 acquisition thread running. Due to python's Global
Interpret Lock, this is not properly at the same time but will alternate
between the 2 threads.

more informations on threading : <https://pymotw.com/2/threading/> more
informations on GIL : <https://wiki.python.org/moin/GlobalInterpreterLock>

