我怎样才能使这两个线程一个接一个地运行python?

时间:2016-08-01 04:57:04

标签: python multithreading loops raspberry-pi threadpool

所以我有这个代码,我需要这两个线程一个接一个地运行。

因此,一旦线程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 个答案:

答案 0 :(得分:1)

这就是你想要的,

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

但是不需要像线程一样运行,你可以调用方法。

while True:
    rfWaterLevelFinal()
    sendDataFinal()