多线程Python:线程通信 [英] Multithreading Python: Thread Communication

查看:117
本文介绍了多线程Python:线程通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python中的threading模块,并已在此处阅读了该教程>.我预期的程序流程是我有2个函数foo()bar(),并且发生以下情况

I'm using the threading module in Python and have read the tutorial here. My intended program flow is that I have 2 functions foo() and bar() and the following happens

1)foo()运行并收集存储在data中的某些数据,然后停止.

1) foo() runs and collects some data stored in data then stops.

2)bar()然后使用data连续运行.

2) bar() then runs continuously using data.

3)2分钟后,foo()再次运行并更新data,而bar()继续使用旧版本的data运行.

3) After 2 minutes foo() runs again and updates data while bar() continues to run using the old version of data.

4)成功更新后,bar()开始使用新版本的数据.

4) After the successful update bar() starts using the new version of data.

5)循环回到(3)

现在我想将它们作为单独的线程运行,而我的问题在于foo()如何告诉bar()它已完成运行并且新版本的data可用?

Now I want to run these as separate threads and my issue lies in how does foo() tell bar() it has finished running and the new version of data is available?

我已经阅读过有关Queue的信息,但无法确切了解在这种情况下如何使用它.

I've read about Queue but couldn't see exactly how I would use it in this instance.

推荐答案

这取决于bar如何消耗数据.如果bar具有可以选择使用现有数据或新数据的自然点,则它可以读取由foo填充的队列.

It depends on how bar consumes the data. If bar has some natural point where it can choose to use existing or new data, it can read a queue filled by foo.

def foo(bar_q):
    while True:
        data = get_some_data()
        # copy or deepcopy if foo will be updating data instead of fetching new
        bar_q.put(copy.copy(data))
        time.sleep(120)

def bar(bar_q):
    # wait for the first data
    data = bar_q.get()
    bar_q.task_done()
    while True:
        process_some_data(data)
        try:
            # get new data if available
            data = bar_q.get_nowait()
            bar_q.task_done()
        except Queue.Empty:
            pass

这篇关于多线程Python:线程通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆