设为首页 加入收藏

TOP

Python 多线程就这么简单(二)
2015-07-16 12:55:47 来源: 作者: 【 】 浏览:50
Tags:Python 线程 这么 简单
':
? ? for t in threads:
? ? ? ? t.setDaemon(True)
? ? ? ? t.start()
? ?
? ? t.join()


? ? print "all over %s" %ctime()


  我们只对上面的程序加了个join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。


  注意:? join()方法的位置是在for循环外的,也就是说必须等待for循环里的两个进程都结束后,才去执行主进程。


运行结果:


>>> ========================= RESTART ================================
>>>
I was listening to 爱情买卖. Thu Apr 17 13:04:11 2014? I was at the 阿凡达! Thu Apr 17 13:04:11 2014


I was listening to 爱情买卖. Thu Apr 17 13:04:12 2014
I was at the 阿凡达! Thu Apr 17 13:04:16 2014
all over Thu Apr 17 13:04:21 2014


  从执行结果可看到,music 和move 是同时启动的。


  开始时间4分11秒,直到调用主进程为4分22秒,总耗时为10秒。从单线程时减少了2秒,我们可以把music的sleep()的时间调整为4秒。


...
def music(func):
? ? for i in range(2):
? ? ? ? print "I was listening to %s. %s" %(func,ctime())
? ? ? ? sleep(4)
...


执行结果:


>>> ====================== RESTART ================================
>>>
I was listening to 爱情买卖. Thu Apr 17 13:11:27 2014I was at the 阿凡达! Thu Apr 17 13:11:27 2014


I was listening to 爱情买卖. Thu Apr 17 13:11:31 2014
I was at the 阿凡达! Thu Apr 17 13:11:32 2014
all over Thu Apr 17 13:11:37 2014


  子线程启动11分27秒,主线程运行11分37秒。


  虽然music每首歌曲从1秒延长到了4 ,但通多程线的方式运行脚本,总的时间没变化。


本文从感性上让你快速理解python多线程的使用,更详细的使用请参考其它文档或资料。


?==========================================================


?==========================================================


class threading.Thread()说明:


class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})


This constructor should always be called with keyword arguments. Arguments are:


  group should be None; reserved for future extension when a ThreadGroup class is implemented.


  target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.


  name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.


  args is the argument tuple for the target invocation. Defaults to ().


  kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.


If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing


anything else to the thread.


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Python 装饰器学习以及实际使用场.. 下一篇使用Python多线程犯的错误总结

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: