繁体   English   中英

是否可以将 pipe 一个线程的结果转换为另一个线程?

[英]Is it possible to pipe the result of one thread into another thread?

我想在另一个线程中使用一个线程的结果(返回值)。

例子:

def foo():
  return "foo"
def bar():
  return "bar"

thread_foo = threading.Thread(target = foo)
thread_bar = threading.Thread(target = bar)

thread_foo.start()
thread_bar.start()

我想做的是使用 function foo的 output 并在 function bar中使用它。

我阅读了文档,但不幸的是没有找到有用的东西。

这是一个使用一个线程的简单示例,但您可以轻松添加更多:

    import Queue
    from threading import Thread
    
    def foo(bar):
        print 'hello {0}'.format(bar)
        return 'foo'
    
    foo_q= Queue.Queue()
    
    t = Thread(target=lambda q, arg1: q.put(foo(arg1)), args=(foo_q, 'world!'))
    t.start()
    t.join()
    result = foo_q.get()
    print result

使用输入队列传递 arguments 和 output 队列获取结果是一种方法。 在以下示例中,thread squarer是一个对其输入参数求平方并“返回”结果的线程。 bar是另一个使用squarer的线程,但也可以很容易地成为主线程:

from threading import Thread
from queue import Queue

in_q = Queue()
out_q = Queue()


def squarer():
    while True:
        x = in_q.get()
        if x is None: # signal to terminate
            return
        out_q.put(x**2) # put answer

def bar():
    for x in (range(10)):
        in_q.put(x)
        result = out_q.get()
        print(f'{x}**2 = {result}')

t1 = Thread(target=squarer)
t1.start()
t2 = Thread(target=bar)
t2.start()
t2.join()
in_q.put(None) # signal thread to terminate
t1.join()

印刷:

0**2 = 0
1**2 = 1
2**2 = 4
3**2 = 9
4**2 = 16
5**2 = 25
6**2 = 36
7**2 = 49
8**2 = 64
9**2 = 81

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM