zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    递归算法转换为非递归算法的技巧
    22. 平面列表
    14. 二分查找
    那点人生小智慧
    9. Fizz Buzz 问题
    8. 旋转字符串
    6. 合并排序数组:
    归并排序
    远方的她
    微服务体系下如何快速构建一个服务
  • 原文地址:https://www.cnblogs.com/plwang1990/p/4374414.html
Copyright © 2011-2022 走看看