【问题标题】:Is it possible to pipe the result of one thread into another thread?是否可以将一个线程的结果通过管道传输到另一个线程?
【发布时间】:2020-12-27 23:30:50
【问题描述】:

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

例子:

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()

我想要做的是使用函数foo的输出并在函数bar中使用它。

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

【问题讨论】:

  • 您可以使用队列在线程之间传递数据docs.python.org/3/library/queue.html 如果您使用多处理,您可以使用管道代替docs.python.org/3/library/…
  • 我修正了主题中的拼写错误,并修正了代码中的两个语法错误。在您寻求帮助之前,请至少尝试运行您的程序。线程共享内存,因此两个线程都可以访问的任何变量都可以用于交换数据。您使用队列来管理并发访问。
  • 如果您需要另一个线程中的一个线程的结果 - 所以一个线程必须等待另一个线程 - 那么线程可能没有意义,更简单的是bar(foo())。最终正常运行第一个函数result = foo() 和后来的Thread(target=bar, args=(result,)。或创建函数 def other(): bar(foo()) 并在 Thread(target=other) 中运行

标签: python python-3.x multithreading python-multithreading


【解决方案1】:

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

    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

【讨论】:

    【解决方案2】:

    使用输入队列传递参数并使用输出队列获取结果是一种方法。在以下示例中,线程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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多