Python3 利用threading.Lock()实现阻塞线程

这是一个Python3 利用threading.Lock()实现线程自我阻塞,被动等着其它线程解除阻塞状态的一个小demonstration。
说人话就是:这是一个Python 3 实现主动暂停线程的一个小范例。。
测试环境:Python 3.8.5
Talk is cheap,show me the code.
没什么好说的,直接上代码。

import time
import threading

class my_thread_lock:
    # wait_time = 0
    # allow_run = False
    # is_running = False
    # wait_time_count = 0

    def __init__(self):
        self.lock = threading.Lock()

    # 获取该锁是否已锁
    def is_locked(self):
        return self.lock.locked()

    # 不管怎么样,宁愿被阻塞,我就是要获取这个锁,
    # 因为我需要独享某个资源
    def just_get_lock(self):
        self.lock.acquire(blocking=True)
        return self.lock.locked()

    # 不管怎么样,宁愿被阻塞,也要锁上这个锁,
    # 哪怕我不是为了使用某个资源,只是为了锁定
    def just_lock(self):
        if( self.lock.locked() == False ):
            self.just_get_lock()
        return self.lock.locked()

    # 我不是为了锁资源的,而纯粹为了阻塞我自己,
    # 封印我自己,只为等到有人解除我的封印
    def block_myself(self):
        self.trylock()
        self.just_get_lock()
        self.unlock()
        return True

    # 尝试锁上,得逞了就得逞了,没得逞也不阻塞
    def trylock(self):
        if( self.lock.locked() ):
            return False
        if( self.lock.acquire(blocking=False) ):
            return self.lock.locked()
        return False

    def unlock(self):
        try:
            self.lock.release()
            return True
        except RuntimeError as e:
            print("my_thread_lock:error =",e)
        return False

def a_fun(diy_lock:my_thread_lock):
    i = 0
    while i < 10:
        time.sleep(0.5)
        print("a_fun: {}".format(str(i)*3))
        i = i +1
        if i == 4:
            print("a_fun: 啊我死了")
            diy_lock.block_myself()
            print("a_fun: 啊,我又活了")

def b_fun(diy_lock:my_thread_lock):
    count = 0
    while not diy_lock.is_locked():
        time.sleep(0.5)
    while True:
        count = count +1
        print("b_fun: a_fun 被封印之后的第{}秒……".format( count ))
        time.sleep(1)
        if count == 6:
            print("b_fun: 给 a_fun 解除封印")
            diy_lock.unlock()
            break

if __name__ == "__main__":
    a_lock = my_thread_lock()
    a_fun_thread = threading.Thread(target=a_fun, daemon=True, args=[a_lock])
    b_fun_thread = threading.Thread(target=b_fun, daemon=True, args=[a_lock])
    a_fun_thread.start()
    b_fun_thread.start()
    a_fun_thread.join()

运行结果:

a_fun: 000
a_fun: 111
a_fun: 222
a_fun: 333
a_fun: 啊我死了
b_fun: a_fun 被封印之后的第1秒……
b_fun: a_fun 被封印之后的第2秒……
b_fun: a_fun 被封印之后的第3秒……
b_fun: a_fun 被封印之后的第4秒……
b_fun: a_fun 被封印之后的第5秒……
b_fun: a_fun 被封印之后的第6秒……
b_fun: 给 a_fun 解除封印
a_fun: 啊,我又活了
a_fun: 444
a_fun: 555
a_fun: 666
a_fun: 777
a_fun: 888
a_fun: 999
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值