Python实现线程并发且按序执行的示例代码

顾言
顾言
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍如何在Python中实现多线程的并发启动与顺序执行。通过利用threading模块的join方法,前一个线程阻塞等待后一个线程启动,从而保证执行顺序。示例代码展示了如何创建10个线程,并验证其按0到9的顺序输出结果及时间戳。

复制代码

Python线程顺序执行实现方案

相关实现代码如下所示:


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


import threading


import time


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


'''''

这是线程的启动函数。


该函数通过 front_thread 参数来控制线程的顺序执行。


'''

记录当前时间 clock()。


模拟耗时操作,休眠 2 秒。


# 如果存在前序线程 front_thread,则等待其运行完成后,再执行当前线程


if front_thread != None:


front_thread.join()


将当前线程名称追加到结果列表 ls_name 中。


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



if __name__ == '__main__':


初始化结果名称列表 ls_result_name 为空。


初始化线程列表 ls_thread 为空。


记录程序开始时间 clock()。


# 依次启动 10 个线程(原文注释为1000,代码range(0,10)实际为10个)


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。


将线程 t 添加到线程列表 ls_thread 中。



# 等待所有线程结束


for t in ls_thread:


t.join()



打印结果名称列表 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 相关产品和应用

全部下载

专题列表