python threading.Lock()

'''
Created on 2013-12-7


@author: Administrator
'''
import threading,time
b=50


l=threading.Lock()


def threadcode():
    global b
    print "thread %s invoked " % threading.currentThread().getName()


    l.acquire()
    try:
        print "thread %s running " % threading.currentThread().getName()
        time.sleep(1)
        b = b+50
        print "thread %s set b to %d " % (threading.currentThread().getName(),b)
    finally:
        l.release()


print "value of b at start of program :",b


childthreads = []


for i in range(1, 5):
    t = threading.Thread(target=threadcode, name="thread-%d" % i)
    t.setDaemon(1)
    t.start()
    childthreads.append(t)
    
    
for t in childthreads:
    t.join()
    

print "new value of b " ,b


output:

value of b at start of program : 50
thread thread-1 invoked 
thread thread-1 running 
thread thread-2 invoked 
thread thread-3 invoked 
thread thread-4 invoked 
thread thread-1 set b to 100 
thread thread-2 running 
thread thread-2 set b to 150 
thread thread-3 running 
thread thread-3 set b to 200 
thread thread-4 running 
thread thread-4 set b to 250 
new value of b  250


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值