python多线程怎样执行函数
2个回答
展开全部
将你需要多线程并发执行的函数放入list中
import threading
threads = []
t1 = threading.Thread(target=函数名,args=参数)
threads.append(t1)启动多线程
if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start()
t.join()更多详细操作help(threading)
#coding=utf-8
import threading
from time import ctime,sleep
# 要启动的函数
def music(func):
for i in range(2):
print "I was listening to %s. %s" %(func,ctime())
sleep(1)
# 要启动的函数
def move(func):
for i in range(2):
print "I was at the %s! %s" %(func,ctime())
sleep(5)
threads = []
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'阿凡达',))
threads.append(t2)
# 函数加入线程列表
if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start()
t.join() #子线程完成运行之前,这个子线程的父线程将一直被阻塞,不会退出
print "all over %s" %ctime()
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询