【Python】用with写一个简单的锁

一、

Python中的with与.NET中的using有着异曲同工之妙
最适合处理这种问题 try...finally...的问题

二、

正好在项目中要用到锁的功能比较适合这个场景就写了一个简单的with锁

三、

感觉Python真的是一种超级简单的语言

class locker():
    def __init__(self, defaultTimeout=10):
        self.__lock__ = threading.Lock()
        if not isinstance(defaultTimeout, int):
            raise TypeError("defaultTimeout 必须是 int 类型")
        self.timeout = defaultTimeout

    def lock(self, timeout=None):
        if isinstance(timeout, int):
            return __lockerContext__(self.__lock__, timeout)
        if timeout is not None:
            raise TypeError("timeout 必须是 int 类型")
        if not isinstance(self.timeout, int):
            raise TypeError("locker.timeout 必须是 int 类型")
        return __lockerContext__(self.__lock__, self.timeout)


class __lockerContext__(object):
    def __init__(self, lock, timeout):
        self.__lock__ = lock
        self.__timeout__ = timeout

    def __enter__(self):
        self.__lock__.acquire(self.__timeout__)

    def __exit__(self, exc_type, exc_value, exc_tb):
        self.__lock__.release()

四、

测试

if __name__ == "__main__":
    import time

    lk = locker(100)


    def testA():
        print("A:进入testA,暂停2秒")
        time.sleep(2)
        print("A:准备获取锁")
        with lk.lock():
            print("A:得到锁,锁2秒")
            time.sleep(2)
            print("A:准备释放锁")
        print("A:释放锁")


    def testB():
        print("B:进入testB,准备获取锁")
        with lk.lock():
            print("B:得到锁,锁5秒")
            for i in range(5):
                print("B:" + str(5 - i))
                time.sleep(1)
            print("B:准备释放锁")
        print("B:释放锁")
        time.sleep(1)
        print("B:准备再次获取锁")
        with lk.lock():
            print("B:得到锁")
            time.sleep(1)
            print("B:准备释放锁")
        print("B:释放锁")


    threading.Thread(target=testA).start()
    threading.Thread(target=testB).start()

五、

结果


你可能感兴趣的:(【Python】用with写一个简单的锁)