其他分享
首页 > 其他分享> > 线程加锁

线程加锁

作者:互联网

加锁的作用:

1、多个线程同时修改同一个全局变量时,确保不被CPU切片阻断

2、加锁会加长执行时间

 

import threading
import time

metalocA = threading.Lock()
# metalocB = threading.Lock

num = 0
def func1():
for i in range(1000000):
global num
metalocA.acquire()
num +=1
metalocA.release()

def func2():
for i in range(1000000):
global num
metalocA.acquire()
num +=1
metalocA.release()

def main():
t1 = threading.Thread(target=func1)
t2 = threading.Thread(target=func2)
s_time = time.time()
t1.start()
t2.start()
t1.join()
t2.join()
e_time = time.time()
print(e_time-s_time)

if __name__ == '__main__':
main()
print(num)

''''
不加锁:
0.1509230136871338
1261326

加锁:
0.4519648551940918
2000000
'''

标签:__,加锁,threading,num,线程,time,metalocA
来源: https://www.cnblogs.com/bigcoolcool/p/16184660.html