shareData
import time
from threading import Thread, Lock
from random import randint
多条线程对一个数据进行操作的时候,可能会出现数据安全/混乱问题。解决问题的方案就对公共的数据进行加锁
1.加锁的方法
一个公共数据对应一个锁对象
在获取数据前加锁,数据操作完成后解锁
注意: 加锁后,加锁的部分会串行执行,但是没加锁的代码还是并行的
class Account:
"""银行账号"""
def __init__(self, name, tel):
self.name = name
self.num = '623223147342798347'
self.balance = 1000
self.tel = tel
# 创建锁对象
self.lock = Lock()
def save(self, money):
"""存钱"""
print('开始存钱')
# 加锁
"""
锁对象.acquire(timeout=超时时间)
"""
self.lock.acquire()
balance = self.balance
time.sleep(3)
self.balance = balance + money
print('存钱结束,当前余额:', self.balance)
# 解锁
self.lock.release()
def pay(self, money):
"""取钱"""
print('开始取钱')
self.lock.acquire()
balance = self.balance
time.sleep(3)
if balance >= money:
self.balance = balance - money
else:
print('余额不足')
print('当前余额:', self.balance)
self.lock.release()
acount = Account('余婷', '15300022703')
# acount.save(1000)
# acount.show()
# acount.pay(500)
# acount.show()
t1 = Thread(target=acount.save, args=(1000,))
t2 = Thread(target=acount.pay, args=(500,))
# t2.start()
# t1.start()
#
#
# t1.join()
# t2.join()
# print(acount.balance)
a = 1000
lock_a = Lock()
def add(num):
print('网络请求,获取数据1')
lock_a.acquire()
global a
a1 = a
time.sleep(3)
a = a1 + num
print(a)
lock_a.release()
def sub(num):
print('网络请求,获取数据2')
lock_a.acquire()
global a
a1 = a
time.sleep(3)
a = a1 - num
print(a)
lock_a.release()
t11 = Thread(target=add, args=(10000,))
t22 = Thread(target=sub, args=(100,))
t11.start()
t22.start()
copy
from copy import copy, deepcopy
拷贝: 将对象中的内容拷贝一份产生一个新的对象。原对象和新对象的地址不同
列表.copy(), 字典.copy(), 列表[:] --- 浅拷贝浅拷贝和深拷贝
1)浅拷贝
新对象 = copy(对象)
创建新的对象,新对象中的内容和原对象中的内容的地址一样(直接拷贝, 地址也是直接赋值)
新对象 = deepcopy(对象)
创建新的对象,原对象中的内容也会拷贝一份产生新的地址, 最终保存新的地址
(不是直接拷贝,地址不是直接赋值,而是拷贝地址对应的对象产生新的地址)
list1 = [1, 2, [3, 4]]
list2 = copy(list1)
print(list1, list2)
print(id(list1), id(list2))
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return str(self.__dict__)
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
self.dog = None
def __repr__(self):
return str(self.__dict__)
p1 = Person('小明', 18, '男')
p1.dog = Dog('大黄', 3)
p2 = deepcopy(p1)
p2.name = '小红'
p2.dog.age = 4
print(p1, p2)
# 浅拷贝和深拷贝
list1 = [1, 2]
list11 = [0, 1, list1]
list22 = copy(list11)
list33 = deepcopy(list11)
list11[2].append(100)
print(list22, list1)
print(list33)