Python3 notes

简介: Python3 notes

关于线程优先级队列( Queue)小结:

首先为了体现 queue 特性,代码中理应避免使用 Lock。

队列之于多线程,在于多任务处理时,不便创建过多线程而消耗过量资源,因此queue模块提供了同步的,线程安全的队列类。

import threading

import queue

import time



classWorker(threading.Thread):

   def __init__(self, name, queue):

       threading.Thread.__init__(self)

       self.name = name

       self.queue = queue

       self.start()  # 执行run()    

   def run(self):

       # 循环,保证接着跑下一个任务        

       whileTrue:

           # 队列为空则退出线程            

           ifself.queue.empty():

               break            

           # 获取一个队列数据

           foo =self.queue.get()

           print(self.getName()+" process "+ str(foo))          

           # 延时1s模拟你要做的事情            

           time.sleep(1)

           # 任务完成            

           self.queue.task_done()



# 队列

queue = queue.Queue()

# 加入10个任务队列

for i in range(10):

   queue.put(i)

# 开3个线程

for i in range(3):

   threadName ='Thread'+ str(i)

   Worker(threadName, queue)

# 所有线程执行完毕后关闭

queue.join()

相关文章
|
5月前
|
Linux Apache Python
Python3 notes
Python3 notes
|
12月前
|
Python
Python3 notes
Python3 notes
|
12月前
|
Python
Python3 notes
Python3 notes
|
12月前
|
Linux Python
Python3 notes
Python3 notes
|
索引 Python
|
存储 数据可视化 API
70个注意的Python小Notes
Python读书笔记:70个注意的小Notes 作者:白宁超 2018年7月9日10:58:18 摘要:在阅读python相关书籍中,对其进行简单的笔记纪要。旨在注意一些细节问题,在今后项目中灵活运用,并对部分小notes进行代码标注。
1321 0
|
Python C语言 .NET
Python chapter 8 learning notes
版权声明:本文为博主原创文章,原文均发表自http://www.yushuai.me。未经允许,禁止转载。 https://blog.csdn.net/davidcheungchina/article/details/78267298 ...
952 0
|
Python
Python chapter 2&3 learning notes
版权声明:本文为博主原创文章,原文均发表自http://www.yushuai.me。未经允许,禁止转载。 https://blog.csdn.net/davidcheungchina/article/details/78243401 方法是Python对数据执行的操作。
1312 0
|
Python
Python chapter 4 learning notes
版权声明:本文为博主原创文章,原文均发表自http://www.yushuai.me。未经允许,禁止转载。 https://blog.csdn.net/davidcheungchina/article/details/78243661 1.
975 0