多线程代码
时间:2010-06-11 来源:hkebao
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 runngin" % threading.currentThread().getName()
time.sleep(2)
b = b + 50
print "Thread %s runngin set b to %s" % (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) #这个方法不错哦。指定一个方法就是run里面做的事情了
t.setDaemon(1) #这个表示的是如果你父线程退出我子线程也要跟着退出
t.start()
childthreads.append(t)
for t in childthreads:
t.join() #表示要等t执行完成之后再搪行
print "new value is ",b
b = 50
l = threading.Lock()
def threadcode():
global b
print "Thread %s invoked" % threading.currentThread().getName()
l.acquire()
try:
print "Thread %s runngin" % threading.currentThread().getName()
time.sleep(2)
b = b + 50
print "Thread %s runngin set b to %s" % (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) #这个方法不错哦。指定一个方法就是run里面做的事情了
t.setDaemon(1) #这个表示的是如果你父线程退出我子线程也要跟着退出
t.start()
childthreads.append(t)
for t in childthreads:
t.join() #表示要等t执行完成之后再搪行
print "new value is ",b
相关阅读 更多 +