【python多线程】 多线程池ThreadPoolExecutor及读写锁readerwriterlock的使用

多线程池用法:

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)

输出结果:

进行写操作
当前已有写任务正在进行
进行读操作
进行读操作
进行读操作
进行读操作
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颢师傅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值