day20-线程数据安全

一、数据间共享

数据的存储跟线程无关;一个进程中的数据在多个数据过程中都可以直接使用

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

# 情况1:在子线程中使用子线程使用主线程的数据
# list1 = [1, 2, 3]
#
#
# def func1():
#     list1.append(100)
#
#
# def func2():
#     list1[0] = 'hello'
#
#
# # func1()
# # print(list1)
# #
# # func2()
# # print(list1)
#
# t1 = Thread(target=func1)
# t2 = Thread(target=func2)
# t1.start()
# t2.start()
#
# t1.join()
# t2.join()
# print(list1)


# 情况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()

二、数据共享安全问题

获取锁对象
获取数据
数据操作完成
释放锁对象
注意:使用锁的时候保证一个数据对应一把锁

import time
from threading import Thread, Lock

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

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


class Account:
    """银行账户类"""
    def __init__(self, name, tel, balance, bank='招商银行'):
        self.bank = bank
        self.card_number = '4572424621235589'
        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)
        time.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
        time.sleep(5)
        self.balance = bl - amount
        self.lock.release()
        print('余额2:', self.balance)
        print('========取钱结束!========')


account = Account('a', '14578498745', 10000)
t1 = Thread(target=account.save_money, args=(10000,))
t2 = Thread(target=account.draw_money, args=(10000, ))

t1.start()
t2.start()
t1.join()
t2.join()
print(account.balance)

account2 = Account('小明', '24587414562', 15000)

三、锁的使用

from threading import *
import time

list1 = [1, 2, 3]

lock = Lock()


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


def func2():
    lock.acquire()
    global list1
    list2 = list1[:]
    time.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)

你可能感兴趣的:(day20-线程数据安全)