码迷,mamicode.com
首页 > 编程语言 > 详细

python线程锁

时间:2016-12-12 20:01:58      阅读:353      评论:0      收藏:0      [点我收藏+]

标签:nal   pytho   获取   pre   简单   imp   import   release   lease   

import time,threading
balance = 0
lock = threading.Lock()
def change_it(n):
    global balance
    balance = balance + n
    balance = balance - n
def run_thread(n):
    for i in range(1000000):
        #先获取锁
        lock.acquire()
        try:
            change_it(n)
        finally:
            #改完了一定要释放锁
            lock.release()

t1 = threading.Thread(target=run_thread,args=(5,))
t2 = threading.Thread(target=run_thread,args=(8,))

t1.start()
t2.start()
t1.join()
t2.join()
print(balance)

线程锁的简单实现。

python线程锁

标签:nal   pytho   获取   pre   简单   imp   import   release   lease   

原文地址:http://www.cnblogs.com/uglyliu/p/6165530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!