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

code
# 不加锁:未加锁部分并发执行,加锁部分串行执行,速度慢,数据安全
from threading import current_thread, Thread, Lock
import os, time
 
n = 100
def task():
    # 未加锁的代码并发运行
    time.sleep(3)
    print('%s start to run' % current_thread().getName())
    global n
    # 加锁的代码串行运行
    lock.acquire()
    temp = n
    time.sleep(0.5)
    n = temp - 1
    lock.release()
 
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 start to run
Thread-2 start to run
Thread-5 start to run
Thread-4 start to run
Thread-3 start to run
主:5.518028020858765 n:95
macname@MacdeMacBook-Pro py %

 

 
 
 
 
 
 
 
 
 
 
 

posted @ 2020-12-26 14:21  anobscureretreat  阅读(118)  评论(0编辑  收藏  举报