【问题标题】:How can I make these two threads run one after the other constantly python?如何让这两个线程一个接一个地不断运行 python?
【发布时间】:2016-08-01 04:57:03
【问题描述】:

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

所以,一旦线程 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 中为此使用线程池,但我不知道如何应用它。

对于我可以做些什么来获得我想要的结果有什么想法吗?

干杯 提前致谢!

【问题讨论】:

  • 你不需要线程顺序运行

标签: python multithreading loops raspberry-pi threadpool


【解决方案1】:

这就是你想要的,

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

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

while True:
    rfWaterLevelFinal()
    sendDataFinal()

【讨论】:

  • 我有点需要将它们作为线程运行,因为第一个方法需要正确运行(因为它接收 rf 数据并且如果在此过程中有任何延迟,它会冻结/延迟所有其他数据)
  • 无论如何你已经提到你需要等到线程 1 完成才能启动线程 2。所以上面的 2 个选项可以正常工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多