3

最近、処理を延期する機能や「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初心者-からありがとう

4

2 に答える 2

23

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()
于 2013-01-29T15:41:48.390 に答える
3

ワーカー スレッドの数は、銀行の出納係の数と考えることができます。したがって、人 (アイテム) は列 (キュー) に並び、銀行の出納係 (ワーカー スレッド) によって処理されます。キューは実際には、スレッドの複雑さを管理するための簡単でよく理解されたメカニズムです。

コードがどのように機能するかを示すために、コードを少し調整しました。

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()
于 2013-01-29T15:31:23.683 に答える