python 包之 threading 多线程
作者:autofelix 时间:2021-06-03 19:54:41
一、创建一个线程
通过实例化
threading.Thread
类创建线程
import threading
def func(s):
print(s)
if __name__ == '__main__':
# 创建线程
thread = threading.Thread(target=func, args=('hello',))
# 启动线程
thread.start()
# 等待线程结束
thread.join()
二、创建多个线程
import threading
def func(s):
print(s)
if __name__ == '__main__':
thread = [
threading.Thread(target=func, args=('1', ))
threading.Thread(target=func, args=('2', ))
]
[t.start() for t in thread]
[t.join() for t in thread]
三、线程同步
使用锁实现线程同步
threading.Lock
是直接通过_thread模块扩展实现的锁只有“锁定”和“非锁定”两种状态
同一个线程获取锁后,如果在释放锁之前再次获取锁会导致当前线程阻塞,除非有另外的线程来释放锁,如果只有一个线程,并且发生了这种情况,会导致这个线程一直阻塞下去,即形成了死锁。
import time
import threading
# 创建锁
lock = threading.Lock()
# 全局变量
global_resource = [None] * 5
def change_resource(para, sleep):
# 请求锁
lock.acquire()
# 这段代码如果不加锁,第一个线程运行结束后global_resource中是乱的,输出为:结果是: ['hello', 'hi', 'hi', 'hello', 'hello']
# 第二个线程运行结束后,global_resource中还是乱的,输出为:结果是: ['hello', 'hi', 'hi', 'hi', 'hi']
global global_resource
for i in range(len(global_resource)):
global_resource[i] = para
time.sleep(sleep)
print("结果是:", global_resource)
# 释放锁
lock.release()
if __name__ == '__main__':
thread = [
threading.Thread(target=change_resource, args=('hi', 2))
threading.Thread(target=change_resource, args=('hello', 1))
]
[t.start() for t in thread]
[t.join() for t in thread]
# 结果是: ['hi', 'hi', 'hi', 'hi', 'hi']
# 结果是: ['hello', 'hello', 'hello', 'hello', 'hello']
四、递归锁
上面线程同步使用的是普通锁,也就是只有锁的状态,并不知道是哪个线程加的锁
这样的话使用普通锁时,对于一些可能造成死锁的情况,可以考虑使用递归锁来解决
递归锁和普通锁的差别在于加入了“所属线程”和“递归等级”的概念
释放锁必须有获取锁的线程来进行释放
import time
import threading
# 使用成一个递归锁就可以解决当前这种死锁情况
rlock_hi = rlock_hello = threading.RLock()
def test_thread_hi():
# 初始时锁内部的递归等级为1
rlock_hi.acquire()
print('线程test_thread_hi获得了锁rlock_hi')
time.sleep(2)
# 如果再次获取同样一把锁,则不会阻塞,只是内部的递归等级加1
rlock_hello.acquire()
print('线程test_thread_hi获得了锁rlock_hello')
# 释放一次锁,内部递归等级减1
rlock_hello.release()
# 这里再次减,当递归等级为0时,其他线程才可获取到此锁
rlock_hi.release()
def test_thread_hello():
rlock_hello.acquire()
print('线程test_thread_hello获得了锁rlock_hello')
time.sleep(2)
rlock_hi.acquire()
print('线程test_thread_hello获得了锁rlock_hi')
rlock_hi.release()
rlock_hello.release()
if __name__ == '__main__':
thread = [
threading.Thread(target=test_thread_hi)
threading.Thread(target=test_thread_hello)
]
[t.start() for t in thread]
[t.join() for t in thread]
五、信号锁
一个信号量管理一个内部计数器
acquire()
方法会减少计数器,release()
方法则增加计数器计数器的值永远不会小于零
当调用
acquire()
时,如果发现该计数器为零,则阻塞线程直到调用
release()
方法使计数器增加。
import time
import threading
# 创建信号量对象,初始化计数器值为3
semaphore3 = threading.Semaphore(3)
def thread_semaphore(index):
# 信号量计数器减1
semaphore3.acquire()
time.sleep(2)
print('thread_%s is running...' % index)
# 信号量计数器加1
semaphore3.release()
if __name__ == '__main__':
# 虽然会有9个线程运行,但是通过信号量控制同时只能有3个线程运行
# 第4个线程启动时,调用acquire发现计数器为0了,所以就会阻塞等待计数器大于0的时候
for index in range(9):
threading.Thread(target=thread_semaphore, args=(index, )).start()
来源:https://blog.51cto.com/autofelix/5167799
标签:python,包,threading,多线程
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python操作PDF实现制作数据报告
2022-05-09 21:41:51
![](https://img.aspxhome.com/file/2023/9/121069_0s.png)
Python标准库之Math,Random模块使用详解
2021-02-09 22:33:13
在Windows的Apache服务器上配置对PHP和CGI的支持
2023-10-20 22:12:17
Python如何筛选序列中的元素的方法实现
2021-06-12 03:31:51
Keras使用ImageNet上预训练的模型方式
2021-03-01 10:08:51
![](https://img.aspxhome.com/file/2023/0/81840_0s.jpg)
Python中random模块生成随机数详解
2023-06-13 16:11:52
分析Python感知线程状态的解决方案之Event与信号量
2022-05-11 07:23:35
![](https://img.aspxhome.com/file/2023/3/76783_0s.jpg)
asp 动态生成rss(不成生xml文件)代码
2011-04-04 11:17:00
使用python matplotlib contour画等高线图的详细过程讲解
2023-10-21 06:29:10
![](https://img.aspxhome.com/file/2023/5/75245_0s.png)
python的数据与matlab互通问题:SciPy
2022-05-16 04:53:48
Python中encode()方法的使用简介
2023-09-22 15:26:38
非常全面的实用JavaScript开发工具列表
2010-01-05 16:44:00
![](https://img.aspxhome.com/file/UploadPic/20101/11/200912311344278032-17s.jpg)
浅谈Python 对象内存占用
2022-04-01 11:21:40
Oracle数据库编写有效事务指导方针
2009-03-19 17:41:00
网站鼠标变变变!
2010-10-20 20:09:00
Python+Opencv实现把图片、视频互转的示例
2022-03-24 23:07:38
国内ASP开源建站系统一览
2009-07-10 13:21:00
Python StringIO模块实现在内存缓冲区中读写数据
2021-12-22 08:23:13
python format格式化和数字格式化
2021-09-04 16:28:31
![](https://img.aspxhome.com/file/2023/5/86545_0s.png)
Python全景系列之数据类型大盘点
2021-01-10 15:29:19