所以我有這個代碼,我需要這兩個線程一個接一個地運行。如何讓這兩個線程一個接一個地不斷運行python?
所以,一旦線程1完成,線程2就會進入,一旦線程2完成,線程1就會進入線程2等......就像不斷循環一樣。
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()
所以基本上我需要這個線程1開始接不完,線程2開始接不完,要不斷地運行(好像它是一個無限循環)。
我已經看過在Python中使用一個線程池,但我不知道如何應用它。
關於我能做些什麼來獲得我想要的結果的想法?
乾杯 在此先感謝!
你不需要線程按順序運行 – YOU