1

キューを使用したPythonマルチスレッドに関する記事を読んでいて、基本的な質問があります。

print stmtに基づいて、5つのスレッドが期待どおりに開始されます。では、キューはどのように機能しますか?

1.スレッドは最初に開始され、キューにアイテムが入力されると、再起動されてそのアイテムの処理が開始されますか?2.キューシステムを使用し、スレッドがキュー内のアイテムごとに各アイテムを処理する場合、パフォーマンスはどのように向上しますか。シリアル処理とは異なります。1x1。

import Queue
import threading
import urllib2
import datetime
import time

hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
"http://ibm.com", "http://apple.com"]

queue = Queue.Queue()

class ThreadUrl(threading.Thread):

  def __init__(self, queue):
    threading.Thread.__init__(self)
    print 'threads are created'
    self.queue = queue

  def run(self):
    while True:
      #grabs host from queue
      print 'thread startting to run'
      now = datetime.datetime.now()

      host = self.queue.get()

      #grabs urls of hosts and prints first 1024 bytes of page
      url = urllib2.urlopen(host)
      print 'host=%s ,threadname=%s' % (host,self.getName())
      print url.read(20)

      #signals to queue job is done
      self.queue.task_done()

start = time.time()
if __name__ == '__main__':

  #spawn a pool of threads, and pass them queue instance 
    print 'program start'
    for i in range(5):

        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

 #populate queue with data   
    for host in hosts:
        queue.put(host)

 #wait on the queue until everything has been processed     
    queue.join()


    print "Elapsed Time: %s" % (time.time() - start)
4

1 に答える 1

1

キューはリストコンテナに似ていますが、データを通信するためのスレッドセーフな方法にするために内部ロックがあります。

すべてのスレッドを開始すると、すべてのスレッドがself.queue.get()呼び出しをブロックし、キューからアイテムをプルするのを待機します。アイテムがメインスレッドからキューに入れられると、スレッドの1つがブロック解除され、アイテムを受け取ります。その後、終了してブロッキング状態に戻るまで処理を続行できます。

すべてのスレッドがキューからアイテムを受信できるため、すべてのスレッドを同時に実行できます。これは、パフォーマンスの向上が見られる場所です。urlopenreadが1つのスレッドで時間がかかり、IOを待機している場合、それは別のスレッドが作業を実行できることを意味します。キューオブジェクトのジョブは、単にロックアクセスを管理し、呼び出し元にアイテムをポップオフすることです。

于 2012-12-05T03:29:48.593 に答える