Chinaunix首页 | 论坛 | 博客
  • 博客访问: 361418
  • 博文数量: 150
  • 博客积分: 3423
  • 博客等级: 中校
  • 技术积分: 1005
  • 用 户 组: 普通用户
  • 注册时间: 2011-07-15 09:04
文章分类

全部博文(150)

文章存档

2012年(2)

2011年(148)

分类: 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
'''

阅读(1182) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~