Python多线程两个并行循环

2024-10-03 21:34:06 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个平行的块循环。使用python并行运行它们的最佳方法是什么。目前我正在使用以下程序进行多线程的实验

#!/usr/bin/env python
import time
import serial
import os
from threading import Thread

ser = serial.Serial(port='/dev/ttyUSB0', baudrate=38400, timeout=None)

ser.flushInput()
ser.flushOutput()

def getstrings(port):
    buf = bytearray()
    while True:
        b = port.read(1)
        if b == b'\x02':
            del buf[:]
        elif b == b'\x03':
            yield buf.decode('ascii')
        else:
            buf.append(b)

def tester():
    while 1:
        print('testing')

def values():
    count = ""
    tem = ""
    hv = ""
    counti = 0
    temi = 0
    hvi = 0

    while 1:
        for item in getstrings(ser):

        #if len(item) >= 10:
         #   continue

            if item[1] == "C":
                count = item.split('C')[1]
                counti=int(count[0:5])


            if item[1] == "T":
                tem = item.split('T')[1]     
                temi=int(tem[0:5])

            if item[1] == "H":
                hv = item.split('H')[1]
                hvi = int(hv[0:5])/10

            print ("HV="+str(hvi)+" "+"Count="+str(counti)+" "+"Temp="+str(temi))

t1 = Thread(target=values)
t2 = Thread(target=tester)
t1.start()
t2.start()

只有第二个线程工作。它不打印秒的值。这是我第一次尝试多线程。一旦我了解了它的功能,我就打算用它来设计一个使用Tkinter库的GUI。我想使用我的程序沿着Tkinter主循环的循环。任何我可能犯错误的建议。你知道吗

更新:

是的,它是线程2而不是线程1。我的错对不起。但是如果我对t1.start()t2.start()进行注释,这两个线程都可以单独工作。但是,只有线程2一起打印输出。你知道吗


Tags: importifportdefcountitem线程thread