python多线程数据同步安全问题(两种解决方案)

import threading

#如果多个线程同时访问同一个资源,就会造成线程得不安全

money = 0

#定义一个函数用于存钱

def addMoney():

    global money

    for i in range(1000000):

        money+=1

    print(money)

#线程冲突情况

def conflict():

    #有五个线程,这五个线程同时取用同一个资源

    for _ in range(5):

        t = threading.Thread(target=addMoney)

        t.start()

    pass

#线程冲突解决方案

#一,线程同步

def threadSync():

    for _ in range(5):

        t = threading.Thread(target=addMoney)

        t.start()

        t.join()#将线程加入同步队列中,同步既是多个线程在同步队列中依次执行,串行

    #同步会造成线程堵塞

    #方案二,给资源加锁

lock = threading.Lock()#互斥锁

def addMoney2():

    global money

    print('当前线程为',threading.current_thread().name)

    # 给公共资源处理过程加锁

    # if lock.acquire():

    #     for i in range(1000000):

    #         money+=1

    #     print(money)

    # #释放

    # lock.release()

    with lock:

        for i in range(1000000):

            money+=1

        print(money)

    print('线程',threading.current_thread().name)

def threadLock():

    for _ in range(5):

        t = threading.Thread(target=addMoney2)

        t.start()


if __name__ == '__main__':

    # conflict()

    # threadSync()

    threadLock()
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值