多线程池用法:
import time
import threading
from concurrent.futures import ThreadPoolExecutor,as_completed
def myCallBack(arg):
print(arg)
return arg
if __name__ == "__main__":
with ThreadPoolExecutor(max_workers=5) as executor:
list = [1,2,3]
ans = [executor.submit(myCallBack, i) for i in list]
for res in as_completed(ans):
print("给出结果",res.result())
输出结果:
1
2
3
给出结果 1
给出结果 2
给出结果 3
thread join success!
多线程加普通锁:
import time
import threading
from concurrent.futures import ThreadPoolExecutor,as_completed
def get():
for i in range(3):
time.sleep(1)
print(i)
def task(lock):
lock.acquire() #获取锁
get()
lock.release() #释放锁
if __name__ == "__main__":
lock=threading.RLock()
with ThreadPoolExecutor(max_workers=5) as executor:
for i in range(5):
ans = [executor.submit(task, lock)]
输出结果:
0
1
2
0
1
2
0
1
2
0
1
2
0
1
2
关于读写锁:
在某些情况下,与常规锁相比,读写锁可以提高程序的性能,但实现起来更复杂,并且通常使用更多资源来跟踪读者的数量。
决定使用哪种类型的互斥锁,一般的经验法则是:当线程从共享数据中读取远多于写入时,使用读写器锁,例如某些类型的数据库应用程序。
如果程序的大多数线程都在写,不建议使用读写锁。
读写锁安装方式:
pip install -i https://pypi.douban.com/simple readerwriterlock
我们使用from readerwriterlock import rwlock命令导入读写锁,这里使用的是Fair版本,意味着读和写享有相同的优先级。读写锁定有两种方法gen_rlock()和gen_wlock()分别生成读锁和写锁,其中读锁可以由多个线程同时拥有,而写锁只能由一个线程掌握。
我们使用rwlock.RWLockFair().gen_rlock().c_rw_lock.v_read_count统计出持有读取锁的线程数.
使用rwlock.RWLockFair().gen_wlock()…v_locked是否为True判断是否写锁激活
多线程加读写锁代码:
import os
import sys
import time
import threading
from concurrent.futures import ThreadPoolExecutor,as_completed
from readerwriterlock import rwlock
lock = rwlock.RWLockFair()
rlock = lock.gen_rlock()
wlock = lock.gen_wlock()
#使用此行代码显示当前正在执行的读任务数rlock.c_rw_lock.v_read_count
writeState=True
def write(lock):
if True:
wlock.acquire()
print("进行写操作")
time.sleep(1)
wlock.release()
else:
print("当前已有读任务正在进行")
def read(lock):
#检测写锁是否上锁
if wlock.v_locked==False:
rlock.acquire()
print("进行读操作")
#time.sleep(1)
rlock.release() # 释放锁
else:
print("当前已有写任务正在进行")
if __name__ == "__main__":
lock = rwlock.RWLockFair()
with ThreadPoolExecutor(max_workers=10) as executor:
for i in range(1):
ans = [executor.submit(write, (lock))]
for i in range(5):
ans = [executor.submit(read, (lock))]
time.sleep(2)
输出结果:
进行写操作
当前已有写任务正在进行
进行读操作
进行读操作
进行读操作
进行读操作