3.线程安全
一个线程中可以有多个子线程,且线程可以共享进程中所有的资源
多个线程去操作一份资源,高概率性的发生数据混乱的情况,如下:
- 示例
import threading
loop = 100000000
number = 0
def _add(count):
global number
for i in range(count):
number += 1
def _sub(count):
global number
for i in range(count):
number -= 1
t1 = threading.Thread(target=_add, args=(loop,))
t2 = threading.Thread(target=_sub, args=(loop,))
t1.start()
t2.start()
t1.join()
t2.join()
print(number)
结果不符合预期
-
加入线程锁,解决“数据混乱”的问题
import threading lock_object = threading.RLock() loop = 100000000 number = 0 def _add(count): lock_object.acquire() # 加锁 global number for i in range(count): number += 1 lock_object.release() # 释放锁 def _sub(count): lock_object.acquire() # 加锁 global number for i in range(count): number -= 1 lock_object.release() # 释放锁 t1 = threading.Thread(target=_add, args=(loop,)) t2 = threading.Thread(target=_sub, args=(loop,)) t1.start() # t1.join()主进程等待子进程 # t1.setDaemo(Ture)主进程结束子进程 t2.start() t1.join() t2.join() print(number)
结果符合预期
-
with 上下文管理锁
import threading lock_object = threading.RLock() loop = 100000000 number = 0 def _add(count): with lock_object: ##上下文管理 global number for i in range(count): number += 1 def _sub(count): with lock_object: ##上下文管理 global number for i in range(count): number -= 1 t1 = threading.Thread(target=_add, args=(loop,)) t2 = threading.Thread(target=_sub, args=(loop,)) t1.start() # t1.join()主进程等待子进程 # t1.setDaemo(Ture)主进程结束子进程 t2.start() t1.join() t2.join() print(number)
-
线程安全的数据类型(内部集成了锁的机制)
import threading lock_object = threading.RLock() data_list=[] def task(): print('start') for i in range(100000000): data_list.append(i) print(len(data_list)) for i in range(10): t=threading.Thread(target=task) t.start()
以下操作为数据安全:
L.append(x)
L1.expend(L2)
x=L(i)
L1[i:j]=L2
L.sort()
x=y
x.field=y
D(x)=y
D1.update(D2)
D.keys()
下面的不是数据安全
i=i+1
L.append(L[-1])
L[i]=L[j]
D(x)=D(x)+1
多注意开文档中是否表明为数据安全
标签:count,python,t2,基础,number,t1,threading,线程 From: https://www.cnblogs.com/xiaoleixiangqianchong/p/17142739.html