【问题标题】:Learning about Queue module in python (how to run it)学习python中的Queue模块(如何运行)
【发布时间】:2013-01-13 04:22:33
【问题描述】:

最近在队列设计中引入了延迟处理的能力以及实现“FIFO”等。

查看文档以尝试获取示例队列以了解如何在我自己的设计/程序中实现它。但是我在运行这段代码时遇到了问题:

import queue

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

def main():

    q = queue.Queue(maxsize=0)
    for i in range(num_worker_threads):
         t = Thread(target=worker)
         t.daemon = True
         t.start()

    for item in source():
        q.put(item)

    q.join()       # block until all tasks are done

main()

问题:希望有人解释 for 循环在做什么,我在运行代码时遇到错误,所以我必须遗漏一些东西。

发生的问题错误: NameError:未定义全局名称“num_worker_threads”

感谢-Python新手-

【问题讨论】:

  • 嗯,你有没有在任何地方定义过 num_worker_threads?
  • @Glycan 我不知道我要定义什么。这就是我想知道的。几乎都是如何使用的。
  • 那个错误意味着你没有定义 num_worker_threads,不管是什么。我不知道 Queue 是什么,并且通常会尽量远离 python 中的线程,但你仍然需要在使用之前定义你的变量。查看文档以了解它应该是什么。
  • 线程实际上在 python 中很有用。您只需要知道何时使用它们。正如 Glycan 所提到的,线程不会极大地帮助您提高处理速度,因为 python 使用称为全局解释器锁的东西。实际上,这意味着在给定时间只有一个线程在运行。但是,线程对于 IO 绑定进程(如读取文件)可能非常强大。在这种情况下,当从内存中检索数据时,存在允许处理继续进行的停机时间。

标签: python multithreading python-3.x queue


【解决方案1】:

for 循环正在启动多个工作线程来执行“worker”定义的功能。这是应该在您的系统上以 python 2.7 运行的工作代码。

import Queue
import threading

# input queue to be processed by many threads
q_in = Queue.Queue(maxsize=0)

# output queue to be processed by one thread
q_out = Queue.Queue(maxsize=0)

# number of worker threads to complete the processing
num_worker_threads = 10

# process that each worker thread will execute until the Queue is empty
def worker():
    while True:
        # get item from queue, do work on it, let queue know processing is done for one item
        item = q_in.get()
        q_out.put(do_work(item))
        q_in.task_done()

# squares a number and returns the number and its square
def do_work(item):
    return (item,item*item)

# another queued thread we will use to print output
def printer():
    while True:
        # get an item processed by worker threads and print the result. Let queue know item has been processed
        item = q_out.get()
        print "%d squared is : %d" % item
        q_out.task_done()

# launch all of our queued processes
def main():
    # Launches a number of worker threads to perform operations using the queue of inputs
    for i in range(num_worker_threads):
         t = threading.Thread(target=worker)
         t.daemon = True
         t.start()

    # launches a single "printer" thread to output the result (makes things neater)
    t = threading.Thread(target=printer)
    t.daemon = True
    t.start()

    # put items on the input queue (numbers to be squared)
    for item in range(10):
        q_in.put(item)

    # wait for two queues to be emptied (and workers to close)   
    q_in.join()       # block until all tasks are done
    q_out.join()

    print "Processing Complete"

main()

每个@handle 的 Python 3 版本

import queue 
import threading

# input queue to be processed by many threads
q_in = queue.Queue(maxsize=0) 

# output queue to be processed by one thread
q_out = queue.Queue(maxsize=0) 

# number of worker threads to complete the processing
num_worker_threads = 10

# process that each worker thread will execute until the Queue is empty
def worker():
    while True:
        # get item from queue, do work on it, let queue know processing is done for one item
        item = q_in.get()
        q_out.put(do_work(item))
        q_in.task_done()

# squares a number and returns the number and its square
def do_work(item):
    return (item,item*item)

# another queued thread we will use to print output
def printer():
    while True:
        # get an item processed by worker threads and print the result. Let queue know item has been processed
        item = q_out.get()
        print("{0[0]} squared is : {0[1]}".format(item) )
        q_out.task_done()

# launch all of our queued processes
def main():
    # Launches a number of worker threads to perform operations using the queue of inputs
    for i in range(num_worker_threads):
         t = threading.Thread(target=worker)
         t.daemon = True
         t.start()

    # launches a single "printer" thread to output the result (makes things neater)
    t = threading.Thread(target=printer)
    t.daemon = True
    t.start()

    # put items on the input queue (numbers to be squared)
    for item in range(10):
        q_in.put(item)

    # wait for two queues to be emptied (and workers to close)   
    q_in.join()       # block until all tasks are done
    q_out.join()

    print( "Processing Complete" )

main()

【讨论】:

  • 这是一个更新 Python 3 模块名称、打印和字符串格式的补丁 ``` 1c1 import queue 5c5 q_in = queue.Queue(maxsize=0) 8c8 q_out = queue.Queue(maxsize=0) 30c30 print("{0[0]} squared is : {0[1]}".format(item) ) 54c54 print("Processing Complete" ) ` ``
【解决方案2】:

您可以将工作线程的数量视为银行出纳员的数量。因此,人们(您的物品)排队(您的队列)由银行出纳员(您的工作线程)处理。队列实际上是一种简单且易于理解的机制来管理线程中的复杂性。

我已经稍微调整了您的代码以显示它是如何工作的。

import queue
import time
from threading import Thread

def do_work(item):
    print("processing", item)

def source():
    item = 1
    while True:
        print("starting", item)
        yield item
        time.sleep(0.2)
        item += 1

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = queue.Queue(maxsize=0)
def main():
    for i in range(2):
        t = Thread(target=worker)
        t.daemon = True
        t.start()

    for item in source():
        q.put(item)

    q.join()       # block until all tasks are done

main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2018-03-03
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    相关资源
    最近更新 更多