【问题标题】:Python 3.9 - Multithreading with queuesPython 3.9 - 带队列的多线程
【发布时间】:2021-08-08 06:30:09
【问题描述】:

我认为这可能是一个简单的问题,但我似乎无法理解这一点。考虑下面的示例代码。

def 1_processing(search_query, q):
    ''' Do some data http data fetching using Python 'Requests' - may take 5 to 20 seconds'''
    q.put(a)
    q.put(b)
    ''' Two to three items to be put into the queue'''

def 2_processing(search_query, q):
    ''' Do some http data fetching using Python 'Requests' - may take 5 to 20 seconds'''
    q.put(x)
    q.put(y)
    q.put(z)
    ''' Two to three items to be put into the queue'''


q = queue.Queue()

''' Start the threads asynchronously'''
t1 = threading.Thread(target=1_processing, args=('search_query', q))
t2 = threading.Thread(target=2_processing, args=('search_query', q))
t1.start()
t2.start()

我正在尝试运行两个异步进程,然后在收到数据后立即使用数据(通过队列),而无需等待其中一个或两个进程完成。

如何在收到队列数据后立即使用它?

我知道我可以做一个简单的 q.get() 但我事先不知道队列大小。我也不想加入 (t1.join, t2.join()) 进程,因为这意味着程序将花费太长时间并且不会在收到数据后立即显示。我希望能够在收到数据后立即显示数据,并且在我从队列中获取数据时知道进程何时完成。

谢谢。

【问题讨论】:

  • 您可能误解了队列范式。我将整理一个示例并尽快作为答案发布

标签: python multithreading queue


【解决方案1】:

queue.Queue 是一个非常有用的类,因为它不仅提供了一种在线程之间传递数据的机制,而且(可选地)有效地限制了并发线程的数量。队列是一个先进先出队列。如果构造时没有参数,那么它的大小是无限的(受内存限制)。但是,如果使用整数参数构造,则该值会限制任何时间点可以在队列中的项目数。如果队列已满,put() 函数将阻塞,直到有可用空间。这是一个简单的例子:-

import queue
import threading

Q = queue.Queue(2)  # limit concurrent threads to 2


def func1(p):
    print(f'{p} -> {Q.get()}')


T = []

for i in range(10):
    t = threading.Thread(target=func1, args=('foo',)) # construct the thread
    Q.put(i) # place a value on the queue - may block
    T.append(t) # add thread reference to list for join later
    t.start() # start the thread

[t.join() for t in T] # wait for all threads to terminate

【讨论】:

  • 感谢@DarkKnight,我很可能误解了应该如何使用队列。让我理解你的例子。请耐心等待,因为我对这一切还很陌生!
猜你喜欢
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多