使用six.moves.queue.put()方法将数据添加到队列中
发布时间:2024-01-01 02:19:41
six.moves.queue.put()方法用于将数据添加到队列中。该方法会将数据添加到队列的末尾,并返回None值。
下面是一个使用例子:
import six.moves.queue as queue
import threading
def producer(q):
for i in range(5):
data = "Data-" + str(i)
q.put(data)
print("Producer put", data, "into the queue.")
print("Queue size:", q.qsize())
print("=" * 20)
def consumer(q):
while True:
data = q.get()
print("Consumer got", data, "from the queue.")
q.task_done()
q = queue.Queue()
t1 = threading.Thread(target=producer, args=(q,))
t2 = threading.Thread(target=consumer, args=(q,))
t1.start()
t2.start()
在这个例子中,我们创建了一个队列(q)并定义了一个生产者(producer)和一个消费者(consumer),它们都操作同一个队列。生产者会生成一些数据,并使用q.put()方法将其放入队列中。消费者会从队列中获取数据,并打印出来。
运行代码后,你会看到生产者不断将数据放入队列中,并打印出队列的大小,消费者不断从队列中获取数据并打印出来。由于生产者和消费者都在不同的线程中执行,因此它们可以同时进行。
在这个例子中,我们使用了six.moves.queue模块的Queue类来创建队列,而不是直接使用queue模块,这是为了保证代码的兼容性。six.moves模块提供了一种方式来让代码在Python 2和Python 3之间兼容,可以使用相同的代码来运行。
