Rlock
# -*-coding:utf-8 -*-
#<征服python--语言基础与典型用例>P153
#简单线程同步,加锁
import threading
import time
class mythread(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self, name = threadname)
def run(self):
global x
lock.acquire()
for i in range(3):
x = x + 1
time.sleep(2)
print x
lock.release()
lock = threading.RLock()
t1 = []
for i in range(10):
t = mythread(str(i))
t1.append(t)
x = 0
for i in t1:
i.start()
'''
output:
3
6
9
12
15
18
21
24
27
30
""
如果不加锁,则会如下结果:
output
30
30
30
30
30
30
30
30
30
30
'''
本文通过一个简单的Python示例介绍了如何使用线程锁(RLock)来实现多线程环境下的数据同步,避免了因并发操作导致的数据不一致问题,并展示了加锁前后程序输出的不同结果。
870

被折叠的 条评论
为什么被折叠?



