Python多线程应用示例
实现任务描述如下:创建多个子线程,共同访问一个队列中的元素,并执行相应操作。
要求要按照元素的执行要按照队列顺序,并且元素的执行不能有重复。
示例代码如下:
#simple sample to show the usage of multithread
import threading
commonlist=range(20)
commonlist.reverse()
class Mythread(threading.Thread):
def __init__(self, lock, threadname):
super(Mythread, self).__init__(name=threadname)
self.lock=lock
def run(self):
global commonlist
flag=True
while(flag):
self.lock.acquire()
if(len(commonlist)==0):
flag=False
else:
item=commonlist.pop()
print "%s get %d"%(self.getName(),item)
self.lock.release()
def main():
lock=threading.Lock()
for i in range(5):
Mythread(lock, "thread-%d"%i).start()
if __name__ == '__main__':
main()
ref:
http://blog.csdn.net/jgood/article/details/4305604
页:
[1]