我有一个线程
(1) 正在监听输入信号,当它收到信号时,另一个线程
(2) 应该执行操作。我正在努力考虑是否应该在两个线程之间共享一个队列,并将函数从 (1) 放入其中,然后在一个大 while 循环中将它们放入 (2) 中。 python
是否提供了在线程之间通信函数调用的更好方法?
最佳答案
我会使用队列。
如果您要使用threading.Condition ,或threading.Event ,我认为没有一种方法可以告诉工作线程有多个输入需要处理。 它们在线程之间提供的通信设备更像是一个切换开关——打开或关闭、通知或等待。
因此,如果 Thread(2) 正在处理一个信号,而 Thread(1) 接收到另一个信号,那么 Thread(1) 将无法很好地告诉 Thread(2) 另一个信号 信号已到达。相反,队列会将所有鸭子(信号)整齐地排成一行,并允许 Thread(2) 逐个处理它们。
import threading
import datetime as DT
import time
import Queue
import random
import itertools
sentinel = None
def worker(queue):
for date, count in iter(queue.get, sentinel):
now = DT.datetime.now()
print('{}: Signal found at {}, processed at {}'
.format(count, date.strftime('%S.%f'), now.strftime('%S.%f')))
time.sleep(random.random()*5)
queue = Queue.Queue()
t = threading.Thread(target=worker, args=(queue, ))
t.daemon = True
t.start()
c = 0
while True:
if random.random() < 0.05:
queue.put((DT.datetime.now(), c))
c += 1
if c >= 5:
# Tell worker to quit
queue.put(sentinel)
t.join()
break
将打印类似的内容
0: Signal found at 27.308544, processed at 27.308705
1: Signal found at 27.308585, processed at 30.379586
2: Signal found at 27.308601, processed at 35.174354
3: Signal found at 27.308607, processed at 36.649155
4: Signal found at 27.308622, processed at 37.234935
请注意,信号都是在 27.3 左右找到/生成的(在主线程中),但直到很久以后才被处理(在工作线程中)。
关于python - 要求另一个线程做某事,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22478059/