【问题标题】:stopping a thread when another thread is done.当另一个线程完成时停止一个线程。
【发布时间】:2016-12-05 15:33:35
【问题描述】:

我正在尝试运行 2 个线程,第一个线程有一个 function1 目标,这个函数应该从机器读取一个值,当这个值 =0 时,输出 0 保存在一个数组中。当此值不再为 0 时,输出 1 应保存在此数组中。然后队列必须返回这个列表。第二个线程有一个function2作为目标,这个函数正在做其他事情。我将尝试在以下代码中显示它:

import threading
from multiprocessing import Queue
def func1(queue_in):
    list=[]
    while value_from_machine==0: #this value will always be refreshed and read again
        list.append(0)
        queue_in.put(list) 
    list.append(1) #when the value from the machine is not 0 anymore, put a 1 in the list
    queue_in.put(list)

def func2():
    #doing something else...

q_out=Queue()

thread1=threading.Thread(target=func1,args=(q_out))
thread2=threading.Thread(target=func2)

thread1.start()
thread2.start()

q_value=q_out.get()

if sum(q_value)==1:
    #print something
else:
    #print something else

现在的问题是我希望第一个线程在第二个线程完成后停止。另一件事是我不确定队列是第一个函数中的输出。在while循环中有队列好不好??

【问题讨论】:

    标签: python multithreading queue python-multithreading


    【解决方案1】:

    标准方法怎么样 - 设置Event

    from threading import Thread, Event
    from Queue import Queue
    from time import sleep
    
    def func1(queue_in, done):
        while not done.is_set():
            queue_in.put_nowait(1)
            print 'func1 added new item to the queue_in'
            sleep(1)
        print 'func1 has finished'
    
    def func2(done):
        x = 0
        while x < 3:
            sleep(2)
            x += 1
            print 'func2 processed %s item(s)' % x
        print 'func2 has finished'
        done.set()
    
    q_out = Queue()
    done  = Event()
    
    thread1 = Thread(target=func1, args=[q_out, done]).start()
    thread2 = Thread(target=func2, args=[done]).start()
    

    输出:

    func1 added new item to the queue_in
    func1 added new item to the queue_in
    func2 processed 1 item(s)
    func1 added new item to the queue_in
    func1 added new item to the queue_in
    func2 processed 2 item(s)
    func1 added new item to the queue_in
    func1 added new item to the queue_in
    func2 processed 3 item(s)
    func2 has finished
    func1 has finished
    

    【讨论】:

    • 不应该在第一个函数中将事件名称作为参数给出吗?然后它将作为第一个线程中的参数给出
    • 确实,如果Event 通过函数参数传递会更好。我更新了我的答案以向您展示任务工作流程。
    • 好的,我认为这是正确的答案,我会尝试,如果它不起作用,这意味着我正在使用的机器将由于其他一些内部原因而崩溃,但我认为这个代码是正确的,谢谢!
    猜你喜欢
    • 2015-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多