
说明
python语言提供了两个与多线程相关的模块,一个是thread模块,另一个是threading模块。
1、thread模块提供的功能和函数相对较少,只提供低水平的线程和简单的锁定。
2、threading模块相对处理多线程的函数较多。
创建使用线程
1 2 3 4 5 6 7 8 | 1 # 导入 thread 模块
2import thread
3 # 创建使用新线程
4thread.start_new_thread ( func, args[, kwargs] )
5 # 参数介绍
6func -- 线程要执行的函数
7args -- 传递给线程的参数,必须是元组类型
8kwargs -- 可选参数
|
线程同步
1 2 3 4 5 6 7 8 9 10 | 1 # 导入 thread 模块
2import thread
3 # 分配锁对象
4lock_ = thread.allocate_lock()
5 # 获取锁对象
6lock_.acquire()
7 # 释放锁对象
8lock_.release()
9 # 查看锁状态
10lock_.locked()
|
以上就是python thread模块实现多线程的方法,希望对大家有所帮助。更多编程基础知识学习:python学习网
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。