如何重复连续运行两个线程

时间:2019-05-19 03:04:38

标签: python multithreading

如果名称 =='主要':     main()

testingNow= test()
t1 = Thread(target = testingNow.addingDataToQueue)

t2 = Thread(target = testingNow.StoringDataComingFromPreviousNode)
t3 = Thread(target = testingNow.readingDataFromQueueFromPreviousNode)
t1.setDaemon(True)


t1.start()
t2.start()
t2.join()
print("Thread t3 will start")


t3.start()
t3.join()
print("Thread t3 Ends")


while True:
    pass

我遇到了一个小问题,我必须一个接一个地连续运行线程t2和t3。请在下面查看我的代码部分。请告诉您将while循环放在哪里。我试图放入while循环,该代码具有无法重新启动线程的错误。我是python的新手。请帮忙。

1 个答案:

答案 0 :(得分:0)

要连续运行线程,应在目标函数内部使用while循环,例如:

from threading import Thread
from queue import Queue
import time

q = Queue()

def foo():
    while True:
        # if you ever use while loops you should use sleep to prevent abusing processor
        time.sleep(0.1)

        # reading q
        if q.qsize():
            msg = q.get()
            # check if we receive a message to quit
            if msg == 'shewawa':
                print('foo is quitting')
                break

            # do your normal jobs here
            if msg == 'test':
                print('foo is running')



t1 = Thread(target=foo)
t1.start()

# test our thread
q.put('test')  # prints 'foo is running'
time.sleep(2)

# send kill code
q.put('shewawa') # Prints 'foo is quitting'

q.put('test') # prints nothing