首页 > 编程语言 > 详细

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

时间:2020-12-26 18:05:25      阅读:35      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!