- 论坛徽章:
- 0
|
python线程HelloWorld
线程同步可以用锁
现在让我们一起回到遥远的DOS时代
还是上面的程序
但是每一时刻只有一个线程可以工作
只是增加了三行代码而已
- #!/usr/bin/env python
- import threading
- import time
- import random
- class PrintThread(threading.Thread):
- def __init__(self, threadName):
- threading.Thread.__init__(self, name = threadName)
- self.sleepTime = random.randint(1,3)
- print "Name: %s; sleep: %d" % (self.getName(), self.sleepTime)
- def run(self):
- lock.acquire() #add this
- print "%s going to sleep for %s second(s)"\
- % (self.getName(), self.sleepTime)
- time.sleep(self.sleepTime)
- print self.getName(), 'done sleeping'
- lock.release() #add this
- num=10
- threadList=[]
- lock=threading.RLock() #add this
- for i in range(1,num+1):
- thread = PrintThread('thread'+str(i))
- threadList.append(thread)
- print '\nStarting threads'
- for i in threadList:
- i.start()
- print 'All threads started\n'
- for i in threadList:
- i.join()
- print 'All threads stoped\n'
复制代码 |
|