python线程通信 消息传递_多线程Python:线程通信

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() runs and collects some data stored in data then stops.

2) bar() then runs continuously using data.

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

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

5) Loop back to (3)

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?

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值