python thread 并发且顺序运行示例 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【meiwen.anslib.com - 电脑资料】

   

    复制代码代码如下:

    #-*- coding:utf-8 -*-

    import threading

    import time

    def fun(name, ls_name, front_thread = None):

    '''''

    线程启动函数

    通过front_thread来使用线程有序的运行

    '''

    time.clock()

    time.sleep(2)

    # 如果front_thread存在,则在front_thread运行完成后,才运行当前线程

    if front_thread != None:

    front_thread.join()

    ls_name.append(name)

    print "thread %s : %s"% (name, time.clock())

    if __name__ == '__main__':

    ls_result_name = []

    ls_thread = []

    time.clock()

    # 逐一启动1000个线程

    for i in range(0,10):

    if len(ls_thread) == 0:

    t = threading.Thread(target=fun, args=(i,ls_result_name,None))

    else:

    t = threading.Thread(target=fun, args=(i,ls_result_name,ls_thread[-1]))

    t.start()

    ls_thread.append(t)

    # 等待所有线程结束

    for t in ls_thread:

    t.join()

    print 'ls_result_name:', ls_result_name

    print "main thread:%s" % time.clock()

    运行结果为:

    thread 0 : 1.99962006344

    thread 1 : 2.00000866032

    thread 2 : 2.00059113658

    thread 3 : 2.00080345407

    thread 4 : 2.00100068584

    thread 5 : 2.00119456523

    thread 6 : 2.00138593033

    thread 7 : 2.00166753037

    thread 8 : 2.00211758757

    thread 9 : 2.0024776892

    ls_result_name: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    main thread:2.003211302

    线程更明细的使用可参考:

    http://docs.python.org/library/threading.html

    time.clock模块的更详细介绍可参考:

    http://blog.csdn.net/kiki113/archive/2009/03/28/4033017.aspx

   

您可能感兴趣的文章:

python线程锁(thread)学习示例

    QQ空间 搜狐微博 人人网 开心网 百度搜藏更多

    Tags:python thread

    复制链接收藏本文打印本文关闭本文返回首页

    上一篇:python 判断一个进程是否存在

    下一篇:windows下wxPython开发环境安装与配置方法

   

相关文章

2014-04-04Python中的map、reduce和filter浅析

2009-05-05python 正则式使用心得

2014-06-06Python中字典(dict)和列表(list)的排序方法实例

2013-12-12用python写asp详细讲解

2012-05-05巧用Python装饰器 免去调用父类构造函数的麻烦

2009-01-01Python Mysql数据库操作 Perl操作Mysql数据库

2013-11-11python读取Android permission文件

2014-04-04python自动安装pip

2008-09-09Python 可爱的大小写

2013-10-10Python sys.path详细介绍

   

文章评论

   

最 近 更 新

   

Python GAE、Django导出Excel的方法

python使用urllib模块开发的多线程豆瓣小

python 中的列表解析和生成表达式

python计算圆周长、面积、球体体积并画出

Python操作Mysql实例代码教程在线版(查询

Python版的文曲星猜数字游戏代码

Python基本数据类型详细介绍

python解析文件示例

Python对两个有序列表进行合并和排序的例

Python 文件和输入输出小结

   

热 点 排 行

   

Python入门教程 超详细1小时学会

python 中文乱码问题深入分析

比较详细Python正则表达式操作指

Python字符串的encode与decode研

Python open读写文件实现脚本

Python enumerate遍历数组示例应

Python 深入理解yield

Python+Django在windows下的开发

python 文件和路径操作函数小结

python 字符串split的用法分享

最新文章