2016-08-01 57 views
1

所以我有這個代碼,我需要這兩個線程一個接一個地運行。如何讓這兩個線程一個接一個地不斷運行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中使用一個線程池,但我不知道如何應用它。

關於我能做些什麼來獲得我想要的結果的想法?

乾杯 在此先感謝!

+1

你不需要線程按順序運行 – YOU

回答

1

這是你想要的,

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

但是,沒有必要像與線程運行,你可以調用的方法。

while True: 
    rfWaterLevelFinal() 
    sendDataFinal() 
+0

我那種需要運行它們作爲一個線程作爲第一個方法需要正確地運行(因爲它接收RF數據,如果有在過程中的任何延遲,它凍結/延遲每一個其他數據) – Verglas

+0

無論如何,你已經提到你需要等到線程1完成後才能啓動線程2.因此,上述2個選項將會像這樣工作 –

相關問題