簡體   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