如何使用 Python 实现多线程队列

pythonserver side programmingprogramming更新于 2026/2/15 16:44:17

简介..

在此示例中,我们将创建一个任务队列,其中包含所有要执行的任务,以及一个与队列交互以单独处理其元素的线程池。

我们将从这个问题开始:什么是队列?队列是一种数据结构,它是以非常特定的顺序维护的不同元素的集合。让我通过一个现实生活中的例子来解释。

假设您在杂货店柜台排队支付杂货账单(不要问我是哪家杂货店)

在等待付账的队伍中,您会注意到以下情况:

1. 人们从队伍的一端进入,从另一端退出。

2.如果 A 先于 B 进入队列,A 就会先于 B 离开队列(除非 B 是名人或有更高的优先权)。

3. 一旦每个人都付了账,队列中就没有人了。

好了,回到编程中,队列的工作方式与此类似。

1. 入队 - 将元素添加到队列末尾。

2. 出队 - 从队列开头移除元素。

还有更多,先进先出 (FIFO) - 先添加的元素将首先被移除。后进先出 (LIFO) - 最后添加的元素将首先被移除。

Python 如何实现队列数据结构?

Python 中的队列模块提供了队列数据结构的简单实现。每个队列可以有以下方法。

  • get():返回下一个元素。

  • put():添加新元素。

  • qsize():队列中当前元素的数量。

  • empty():返回布尔值,表示队列是否为空。

  • full():返回布尔值,表示队列是否已满。

1. 我们将创建一个函数,该函数接受一个参数 x,然后遍历 1 和其本身(x)之间的数字,以执行乘法。例如当您将 5 传递给此函数时,它会从 1 迭代到 5 并不断相乘,即 1 乘以 5、2 乘以 5、3 乘以 5、4 乘以 5、5 乘以 5,最后将值作为列表返回。

示例

def print_multiply(x):
output_value = []
for i in range(1, x + 1):
output_value.append(i * x)
print(f"Output \n *** The multiplication result for the {x} is - {output_value}")
print_multiply(5)

输出

*** The multiplication result for the 5 is - [5, 10, 15, 20, 25]

2.我们将编写另一个名为 process_queue() 的函数,它将尝试获取队列对象的下一个元素。 这个逻辑非常简单,继续传递元素直到队列为空。我将使用 sleep 来延迟处理。

示例

def process_queue():
while True:
try:
value = my_queue.get(block=False)
exceptqueue.Empty:
return
else:
print_multiply(value)
time.sleep(2)

3.创建一个类,当初始化并启动新实例时,将调用 process_queue() 函数。

示例

class MultiThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name

def run(self):
print(f" ** Starting the thread - {self.name}")
process_queue()
print(f" ** Completed the thread - {self.name}")

4.最后,我们将传递数字输入列表并填充队列。

# 设置变量
input_values = [5, 10, 15, 20]

# 填充队列
my_queue =queue.Queue()
for x in input_values:
my_queue.put(x)

5.最后,将所有内容放在一起。

import queue
import threading
import time

# Class
class MultiThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name

def run(self):
print(f"Output \n ** Starting the thread - {self.name}")
process_queue()
print(f" ** Completed the thread - {self.name}")

# 处理队列
def process_queue():
while True:
try:
value = my_queue.get(block=False)
exceptqueue.Empty:
return
else:
print_multiply(value)
time.sleep(2)

# 乘法函数
def print_multiply(x):
output_value = []
for i in range(1, x + 1):
output_value.append(i * x)
print(f" \n *** The multiplication result for the {x} is - {output_value}")

# 输入变量
input_values = [2, 4, 6, 5,10,3]

# 填充队列
my_queue =queue.Queue()
for x in input_values:
my_queue.put(x)
# 初始化并启动 3 个线程
thread1 = MultiThread('First')
thread2 = MultiThread('Second')
thread3 = MultiThread('Third')
thread4 = MultiThread('Fourth')

# 启动线程
thread1.start()
thread2.start()
thread3.start()
thread4.start()

# 加入线程
thread1.join()
thread2.join()
thread3.join()
thread4.join()

输出

** Starting the thread - First
*** The multiplication result for the 2 is - [2, 4]

输出

** Starting the thread - Second
*** The multiplication result for the 4 is - [4, 8, 12, 16]

输出

** Starting the thread - Third
*** The multiplication result for the 6 is - [6, 12, 18, 24, 30, 36]

输出

** Starting the thread - Fourth
*** The multiplication result for the 5 is - [5, 10, 15, 20, 25]
*** The multiplication result for the 10 is - [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
*** The multiplication result for the 3 is - [3, 6, 9] ** Completed the thread - Third
** Completed the thread - Fourth
** Completed the thread - Second ** Completed the thread - First

6.我们已成功实现队列概念。瞧,我们有 4 个线程,但要处理 6 个值,因此最先进入队列的人将被执行,其他人将排队等待其他人完成。

这类似于现实生活,假设有 3 个柜台,但有 10 个人在等着付账,因此 10 个人将排在 3 个队列中,完成付账的人将离开队列并为下一个人让路。


相关文章


有用资源