###########征服Python#########
1 简单的线程同步
##注释掉acquire和release之后,由于i是全局变量,在每个线程对i进行操作后就休眠了,
##在线程休眠的时候,Python解释器已经执行了其他的线程,使i增加。
##当使用Lock对对象的脚本中,对全局变量i的操作放在acquire和release之间,Python解释器每次
##只允许一个线程对i进行操作。只有当该线程操作完后,才开始进行下一个线程
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(1)
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()
2 队列的使用
###使用queue队列保持线程同步
import threading
import time
import Queue
class Producer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name=threadname)
def run(self):
global queue
queue.put(self.getName())
print self.getName(),'put',self.getName(),'to queue'
class consumer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name=threadname)
def run(self):
global queue
print self.getName(),'get',self.getName(),'from queue'
queue=Queue.Queue()
plist=[]
clist=[]
for i in range(10):
p=Producer("Producer"+str(i))
plist.append(p)
for i in range(10):
c=consumer("consumer"+str(i))
clist.append(c)
for i in plist:
i.start()
i.join()
for i in clist:
i.start()
i.join()