2019-08-17day20总结线程数据安全

一、线程数据共享

"""__author__ = YuTing"""
from threading import Thread

总结: 数据的存储跟线程无关;一个进程中的数据在多个线程中可以直接用

情况一: 在子线程中使用主线程中的数据
list1 = [1, 2, 3]


def func1():
    list1.append(100)


def func2():
    list1[0] = 'hello'


t1 = Thread(target=func1)
t2 = Thread(target=func2)
t1.start()
t2.start()

t1.join()
t2.join()
print(list1)    # ['hello', 2, 3, 100]

情况2: 在子线程中使用子线程中产生的数据
def func1():
    global list1
    list1 = [1, 2, 3]



def func2():
    t = Thread(target=func1)
    t.start()
    print(list1)


t1 = Thread(target=func2)
t1.start()

二、线程数据安全问题

"""__author__ = YuTing"""
from time import sleep
from threading import Thread, Lock

"""
获取锁对象
获取数据
数操作完成后
释放锁对象

注意: 使用锁的时候保证一个数据对应一把锁
"""


class Account:
    """银行账号类"""
    def __init__(self, name, tel, balance, bank='招商银行'):
        self.bank = bank
        self.card_number = '6233392838382383'
        self.name = name
        self.tel = tel
        self.balance = balance
        self.lock = Lock()    # 1.创建锁(保证一个数据一把锁)

    def save_money(self, amount):
        print('=====开始存钱!======')
        # 2.使用锁
        self.lock.acquire()
        # 获取余额
        bl = self.balance
        # print('存钱余额1:',bl)
        sleep(2)
        self.balance = bl + amount
        # 3.释放锁
        self.lock.release()
        # print('存钱余额2:', self.balance)
        print('=====存钱结束!======')


    def draw_money(self, amount):
        print('=====开始取钱!======')
        self.lock.acquire()
        bl = self.balance
        # print('取钱余额1:', bl)
        if bl < amount:
            print('余额不足!')
            print('=====取钱结束======')
            return
        sleep(3)
        self.balance = bl - amount
        self.lock.release()
        # print('取钱余额2:', self.balance)
        print('=====取钱结束======')


account = Account('余婷', '153000782', 10000)

t1 = Thread(target=account.save_money, args=(20000,))
t2 = Thread(target=account.draw_money, args=(5000,))
t1.start()
t2.start()
t1.join()
t2.join()
print(account.balance)


account2 = Account('小明', '23782738738', 1000)

三、锁的使用

"""__author__ = YuTing"""
from threading import *
from time import sleep


list1 = [1, 2, 3]
lock = Lock()

def func1():
    lock.acquire()
    global list1
    list2 = list1[:]
    sleep(3)
    list2.append(100)
    list1 = list2[:]
    lock.release()


def func2():
    lock.acquire()
    global list1
    list2 = list1[:]
    sleep(3)
    list2.remove(2)
    list1 = list2[:]
    lock.release()


t1 = Thread(target=func1)
t2 = Thread(target=func2)
t1.start()
t2.start()
t1.join()
t2.join()
print(list1)

你可能感兴趣的:(2019-08-17day20总结线程数据安全)