实现任务描述如下:

创建多个子线程,共同访问一个队列中的元素,并执行相应操作。
要求要按照元素的执行要按照队列顺序,并且元素的执行不能有重复。

示例代码如下:

#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

 

相关文章:

  • 2021-10-07
  • 2021-10-25
  • 2021-07-10
  • 2022-12-23
  • 2021-06-26
  • 2021-11-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-12
  • 2022-01-07
  • 2022-12-23
  • 2021-11-10
  • 2022-01-13
相关资源
相似解决方案