Python模块Threading简介
Python模块Threading用以实现多线程
在Python多线程中,我们可以通过thread和 Threading这两个模块来实现的。Threading模块是对thread做了一些封装的,可以更加方便的使用。
Python模块threading语法结构
1 |
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}) |
group恒为None,保留未来使用。target为执行的函数。name为线程名,默认为Thread-N,通常使用默认即可。但服务器端程序线程功能不同时,建议命名,args为函数的参数。
Python模块threading方法的使用实例
我们通过两个实例来看看threading模块怎么使用。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#coding=utf-8 #auth py40.com 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() print "all over %s" %ctime() |
运行结果
1 2 3 4 5 |
I was listening to 凡人歌. Thu Apr 17 13:04:11 2014 I was at the 阿凡达! Thu Apr 17 13:04:11 2017 I was listening to 黑客帝国. Thu Apr 17 13:04:12 2017 I was at the 凡人歌! Thu Apr 17 13:04:16 2017 all over Thu Apr 17 13:04:21 2017 |
1 2 3 |
threads = [] t1 = threading.Thread(target=music,args=(u'爱情买卖',)) threads.append(t1) |
创建了threads数组,创建线程t1,使用threading.Thread()方法,在这个方法中调用music方法target=music,args方法对music进行传参。 把创建好的线程t1装到threads数组中。
接着以同样的方式创建线程t2,并把t2也装到threads数组。
1 2 3 |
for t in threads: t.setDaemon(True) t.start() |
最后通过for循环遍历线程数组,并启动。
1 |
setDaemon() |
setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去,当父线程执行完最后一条语句print “all over %s” %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。
1 |
start() |
最后别忘了启动线程
未经允许不得转载:Python在线学习 » Python模块Threading用以实现多线程