python thread and lock basic usage 2023-04-06

# -*- coding: utf-8 -*-

import threading
from functools import wraps

shared_resource_with_lock = 0
shared_resource_with_no_lock = 0
COUNT = 1000000
shared_resource_lock = threading.Lock()

def with_lock(l: threading.Lock):
    """
    with_lock return a decorator to lock before op and unlock after op
    """
    def wrapper(f):

        # https://stackoverflow.com/questions/308999/what-does-functools-wraps-do
        @wraps(f)
        def inner(*args, **kw):
            l.acquire()
            try:
                res = f(*args, **kw)
            finally:
                l.release()
            return res
        return inner
    return wrapper

@with_lock(l=shared_resource_lock)
def add1():
    global shared_resource_with_lock
    shared_resource_with_lock += 1

@with_lock(l=shared_resource_lock)
def del1():
    global shared_resource_with_lock
    shared_resource_with_lock -= 1

def add_1():
    global shared_resource_with_no_lock
    shared_resource_with_no_lock += 1

def del_1():
    global shared_resource_with_no_lock
    shared_resource_with_no_lock -= 1

# 有锁的情况
def increment_with_lock():
    for _ in range(COUNT):
        add1()

def decrement_with_lock():
    for _ in range(COUNT):
        del1()

# 没有锁的情况
def increment_without_lock():
    for _ in range(COUNT):
        add_1()

def decrement_without_lock():
    for _ in range(COUNT):
        del_1()

if __name__ == "__main__":
    t1 = threading.Thread(target=increment_with_lock)
    t2 = threading.Thread(target=decrement_with_lock)
    t3 = threading.Thread(target=increment_without_lock)
    t4 = threading.Thread(target=decrement_without_lock)
    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t1.join()
    t2.join()
    t3.join()
    t4.join()
    print ("the value of shared variable with lock management is %s" % shared_resource_with_lock)
    print ("the value of shared variable with race condition is %s" % shared_resource_with_no_lock)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 中原焦点团队网络初级38期何晓晨分享第221天20230406 很喜欢的一段话:在这个世界上,真正可供我们选择的路...
    晨love阅读 69评论 0 0
  • 3月28日至29日,省委书记周祖翼先后赴三明市尤溪县、三元区、明溪县、永安市,深入农村、企业一线,与基层干部群众面...
    小马哒哒SJ阅读 106评论 0 0
  • 昨天提了分手了提之前还是很难受 提完之后好像就放松下来了 之前那段时间整个人都挺消极郁闷的 也影响了家里人 人还是...
    林拉米阅读 125评论 0 1
  • 治疗青少年癫痫方法有哪些? 癫痫是人们俗称的羊癫痫疯,它是一种慢性疾病,具有反复性、突发性的特点,癫痫是一种常见的...
    癫痫之家阅读 71评论 0 0
  • 张雲芳 焦点解决网络课程学习坚持分享第1452天 20230406(约练总435) 1.教育是人类有目的地培养人...
    2018心如止水阅读 67评论 0 0