Python-multithreading

提供:Dev Guides
移動先:案内検索

Python-マルチスレッドプログラミング

複数のスレッドを実行すると、複数の異なるプログラムを同時に実行することに似ていますが、次の利点があります-

  • プロセス内の複数のスレッドはメインスレッドと同じデータ空間を共有するため、別々のプロセスである場合よりも簡単に情報を共有したり、相互に通信したりできます。
  • スレッドはライトウェイトプロセスと呼ばれることもあり、多くのメモリオーバーヘッドを必要としません。プロセスよりも安価です。

スレッドには、開始、実行シーケンス、および結論があります。 コンテキスト内で現在実行されている場所を追跡する命令ポインターがあります。

  • 先取り(中断)することができます
  • 他のスレッドが実行されている間、一時的に保留(スリープとも呼ばれます)できます-これは、譲歩と呼ばれます。

新しいスレッドの開始

別のスレッドを生成するには、_thread_モジュールで利用可能な次のメソッドを呼び出す必要があります-

thread.start_new_thread ( function, args[, kwargs] )

このメソッド呼び出しにより、LinuxとWindowsの両方で新しいスレッドを高速かつ効率的に作成できます。

メソッド呼び出しはすぐに戻り、子スレッドが開始され、_args_の渡されたリストで関数を呼び出します。 関数が戻ると、スレッドは終了します。

ここで、_args_は引数のタプルです。引数を渡さずに関数を呼び出すには、空のタプルを使用します。 _kwargs_は、キーワード引数のオプションの辞書です。

#!/usr/bin/python

import thread
import time

# Define a function for the thread
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )

# Create two threads as follows
try:
   thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print "Error: unable to start thread"

while 1:
   pass

上記のコードが実行されると、次の結果が生成されます-

Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009

低レベルのスレッド化には非常に効果的ですが、_thread_モジュールは新しいスレッド化モジュールに比べて非常に制限されています。

_Threading_モジュール

Python 2.4に含まれている新しいスレッドモジュールは、前のセクションで説明したスレッドモジュールよりも強力で高レベルなスレッドのサポートを提供します。

_threading_モジュールは_thread_モジュールのすべてのメソッドを公開し、いくつかの追加のメソッドを提供します-

  • * threading.activeCount()*-アクティブなスレッドオブジェクトの数を返します。
  • * threading.currentThread()*-呼び出し元のスレッドコントロール内のスレッドオブジェクトの数を返します。
  • * threading.enumerate()*-現在アクティブなすべてのスレッドオブジェクトのリストを返します。

メソッドに加えて、スレッド化モジュールには、スレッド化を実装する_Thread_クラスがあります。 _Thread_クラスによって提供されるメソッドは次のとおりです-

  • * run()*-run()メソッドは、スレッドのエントリポイントです。
  • * start()*-start()メソッドは、runメソッドを呼び出してスレッドを開始します。
  • * join([time])*-join()はスレッドが終了するのを待ちます。
  • * isAlive()*-isAlive()メソッドは、スレッドがまだ実行中かどうかを確認します。
  • * getName()*-getName()メソッドは、スレッドの名前を返します。
  • * setName()*-setName()メソッドは、スレッドの名前を設定します。

_Threading_モジュールを使用したスレッドの作成

スレッドモジュールを使用して新しいスレッドを実装するには、次を行う必要があります-

  • _Thread_クラスの新しいサブクラスを定義します。
  • _ init(self [、args])_メソッドをオーバーライドして、引数を追加します。
  • 次に、run(self [、args])メソッドをオーバーライドして、開始時にスレッドが行うべきことを実装します。

新しい_Thread_サブクラスを作成したら、そのインスタンスを作成し、_start()_を呼び出して新しいスレッドを開始し、_run()_メソッドを呼び出します。

#!/usr/bin/python

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
   def __init__(self, threadID, name, counter):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.counter = counter
   def run(self):
      print "Starting " + self.name
      print_time(self.name, 5, self.counter)
      print "Exiting " + self.name

def print_time(threadName, counter, delay):
   while counter:
      if exitFlag:
         threadName.exit()
      time.sleep(delay)
      print "%s: %s" % (threadName, time.ctime(time.time()))
      counter -= 1

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()

print "Exiting Main Thread"

上記のコードが実行されると、次の結果が生成されます-

Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2

スレッドの同期

Pythonで提供されるスレッドモジュールには、スレッドを同期するための実装が簡単なロックメカニズムが含まれています。 新しいロックを返すには、_Lock()_メソッドを呼び出して新しいロックを作成します。

新しいロックオブジェクトの_acquire(blocking)_メソッドは、スレッドを強制的に同期的に実行するために使用されます。 オプションの_blocking_パラメーターを使用すると、スレッドがロックの取得を待機するかどうかを制御できます。

_blocking_が0に設定されている場合、スレッドは、ロックを取得できない場合はすぐに0の値を返し、ロックが取得された場合は1を返します。 ブロックが1に設定されている場合、スレッドはブロックし、ロックが解除されるのを待ちます。

新しいロックオブジェクトの_release()_メソッドは、不要になったときにロックを解除するために使用されます。

#!/usr/bin/python

import threading
import time

class myThread (threading.Thread):
   def __init__(self, threadID, name, counter):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.counter = counter
   def run(self):
      print "Starting " + self.name
      # Get lock to synchronize threads
      threadLock.acquire()
      print_time(self.name, self.counter, 3)
      # Free lock to release next thread
      threadLock.release()

def print_time(threadName, delay, counter):
   while counter:
      time.sleep(delay)
      print "%s: %s" % (threadName, time.ctime(time.time()))
      counter -= 1

threadLock = threading.Lock()
threads = []

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()

# Add threads to thread list
threads.append(thread1)
threads.append(thread2)

# Wait for all threads to complete
for t in threads:
    t.join()
print "Exiting Main Thread"

上記のコードが実行されると、次の結果が生成されます-

Starting Thread-1
Starting Thread-2
Thread-1: Thu Mar 21 09:11:28 2013
Thread-1: Thu Mar 21 09:11:29 2013
Thread-1: Thu Mar 21 09:11:30 2013
Thread-2: Thu Mar 21 09:11:32 2013
Thread-2: Thu Mar 21 09:11:34 2013
Thread-2: Thu Mar 21 09:11:36 2013
Exiting Main Thread

マルチスレッドプライオリティキュー

_Queue_モジュールを使用すると、特定の数のアイテムを保持できる新しいキューオブジェクトを作成できます。 キューを制御するには、次の方法があります-

  • * get()*-get()は、キューからアイテムを削除して返します。
  • * put()*-putは、アイテムをキューに追加します。
  • * qsize()*-qsize()は、現在キューにあるアイテムの数を返します。
  • * empty()*-empty()は、キューが空の場合にTrueを返します。それ以外の場合、False。
  • * full()*-キューがいっぱいの場合、full()はTrueを返します。それ以外の場合、False。

#!/usr/bin/python

import Queue
import threading
import time

exitFlag = 0

class myThread (threading.Thread):
   def __init__(self, threadID, name, q):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.q = q
   def run(self):
      print "Starting " + self.name
      process_data(self.name, self.q)
      print "Exiting " + self.name

def process_data(threadName, q):
   while not exitFlag:
      queueLock.acquire()
         if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print "%s processing %s" % (threadName, data)
         else:
            queueLock.release()
         time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1

# Create new threads
for tName in threadList:
   thread = myThread(threadID, tName, workQueue)
   thread.start()
   threads.append(thread)
   threadID += 1

# Fill the queue
queueLock.acquire()
for word in nameList:
   workQueue.put(word)
queueLock.release()

# Wait for queue to empty
while not workQueue.empty():
   pass

# Notify threads it's time to exit
exitFlag = 1

# Wait for all threads to complete
for t in threads:
   t.join()
print "Exiting Main Thread"

上記のコードが実行されると、次の結果が生成されます-

Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread