分类: Python/Ruby
2011-10-12 00:03:56
# -*-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
'''