Cucco’s Compute Hack

コンピュータ関係の記事を書いていきます。

QueueをつかったPython マルチスレッド

マルチスレッドのテストプログラム。
Listをもらって、加算して、結果をグローバルのリストに書き込む。

import threading
import queue
import time

commonList=[]
q=queue.Queue()

def worker():
	"""
		マルチスレッドで走らせる関数
		Queueからデータをもらう。
		結果をcommonListに書き込む
		計算内容や書き込む場所はqに書いてある
	"""
	global q
	global commonList
	print("thread Start")
	
	while True:
		time.sleep(0.1) #Ctrl+Cで終了させるおまじない。
		item = q.get()
		if item is None:
			print("thread None")
			break
		commonList.append((item.ID,sum(item.values)))
		q.task_done()
	print("thread End")

def main():
	global q
	global commonList
	num_worker_threads=3
	a=Job([1,2,3],0)
	b=Job([3,4,5],1)
	c=Job([6,7,8],2)
	d=Job([9,0,1],3)
	e=Job([2,3,4],4)
	f=Job([5,6,7,8],5)
	
	threadItem=[a,b,c,d,e,f]
	
	threads=[]
	
	#スレッドを立てる。作業はあとでQueueで渡す。
	for i in range(num_worker_threads):
		t = threading.Thread(target=worker)
		t.start()
		threads.append(t)
	
	#itemを投入。データを渡す。
	for item in threadItem:
		q.put(item)
	
	# block until all tasks are done qが空になるのを待っている。
	q.join()

	#スレッド停止命令(None)の投入
	for i in range(num_worker_threads):
		q.put(None)
	
	#スレッドの終了まち
	for t in threads:
		t.join()
	
	#結果の表示
	print(commonList)

class Job():
	#xはリスト,yは書き込み先のリストのインデックス
	def __init__(self,x,y):
		self.values=x.copy()
		self.ID=y

if __name__ == '__main__':
	main()

結果

C:\Python34>python multiThreadTest.py
thread Start
thread Start
thread Start
thread None
thread End
thread None
thread End
thread None
thread End
[(0, 6), (1, 12), (2, 21), (3, 10), (4, 9), (5, 26)]