'''
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()
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