Verglas Verglas - 4 months ago 14
Python Question

How can I make these two threads run one after the other constantly python?

so I have this code where I need these two threads to be run one after the other CONSTANTLY.

So, once thread 1 finishes, thread 2 goes and once thread 2 finishes, then thread 1 goes then thread 2 etc...like constantly as if it's an infinite loop.

import httplib, urllib
import time, sys
import serial
from threading import Thread
#from multiprocessing import Process

key = 'MY API KEY' #API Key required for ThingSpeak.
rfWaterLevelVal = 0 #Global variable that holds the final water level value.

ser = serial.Serial('/dev/ttyUSB0',9600)

#Gathers the rf data received and separated it to obtain the water level data.
def rfWaterLevel():
global rfWaterLevelVal
rfDataArray = ser.readline().strip().split()
print 'incoming: %s' %rfDataArray
if len(rfDataArray) == 5:
rfWaterLevelVal = float(rfDataArray[4])
print 'RFWater Level1: %.3f cm' % (rfWaterLevelVal)

#Created purely to making the multithreading easier.
def rfWaterLevelFinal():
while True:
try:
rfWaterLevel()
except KeyboardInterrupt:
print "caught keyboard interrupt"
sys.exit()

#Sends the sensor data over to ThingSpeak.
def sendData():
global rfWaterLevelVal

params = urllib.urlencode({'field1':rfWaterLevelVal, 'key':key})
headers = {"Content-type" : "application/x-www-form-urlencoded","Accept": "text/plain"}
conn = httplib.HTTPConnection("api.thingspeak.com:80", timeout = 5)
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
conn.close()

#Created purely to make multithreading easier.
def sendDataFinal():
while True:
try:
sendDataFinal()
except KeyboardInterrupt:
print "caught keyboard interrupt"
sys.exit()

#start thread 1 for rf water level data.
t1 = Thread(target = rfWaterLevelFinal())
t1.start()

#start thread 2 for sending the data.
t2 = Thread(target = sendDataFinal())
t2.start()

#wait for both threads to finish
t1.join()
t2.join()


So essentially I need this thread 1 start then finish, thread 2 start then finish, to be constantly run (as if it's in an infinite loop).

I have looked at using a threadpool for this in python but i have no clue how to apply it.

Any ideas on what I could do to get the results that I want?

Cheers
Thanks in Advance!

Answer

This is what you wanted,

while True:
    t1 = Thread(target = rfWaterLevelFinal())
    t1.start()
    t1.join()
    t2 = Thread(target = sendDataFinal())
    t2.start()
    t2.join()

But no need to run like that with threads, you can just call the methods.

while True:
    rfWaterLevelFinal()
    sendDataFinal()
Comments