不加线程锁对公共资源进行修改

code
# 不加锁:并发执行,速度快,数据不安全
from threading import current_thread, Thread, Lock
import os, time
 
 
n = 100
def task():
    global n
    print('%s is running' % current_thread().getName())
    temp = n
    time.sleep(0.5)
    n = temp - 1
 
 
if __name__ == '__main__':
    
    lock = Lock()
    threads = []
    start_time = time.time()
    for i in range(5):
        t = Thread(target=task)
        threads.append(t)
        t.start()
    for t in threads:
        t.join()
 
 
    stop_time = time.time()
    print('主:%s n:%s' % (stop_time - start_time, n))
 
outputs
macname@MacdeMacBook-Pro py % python3 cccccc.py
Thread-1 is running
Thread-2 is running
Thread-3 is running
Thread-4 is running
Thread-5 is running
主:0.503460168838501 n:99
macname@MacdeMacBook-Pro py %
 
 
 
 
 
 
 
 
 
 
 
 
 

原文地址:https://www.cnblogs.com/sea-stream/p/14192789.html