您的位置:首页 > 编程语言 > Python开发

python多线程编程

2017-03-06 20:37 274 查看

python多线程编程架构

import Queue
import threading
import subprocess

q = Queue.Queue()
for i in range(30): #put 30 tasks in the queue
q.put(i)

def worker():  #replace worker with you want to parallel preprocess
while True:
item = q.get()
#execute a task: call a shell program and wait until it completes
subprocess.call("echo "+str(item), shell=True)
q.task_done()

cpus=numofyourcpu #detect number of cores
print("Creating %d threads" % cpus)
for i in range(cpus):
t = threading.Thread(target=worker)
t.daemon = True
t.start()

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

reference
my demo

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: