python求職準備第4天—進程優先級隊列

昨天覆習了線程以及線程的同步,今天覆習線程優先級隊列 使用queue  之前講過 queue.Queue是服務線程的 而Queue 是服務進程的,這個要注意。

線程優先級隊列示例如下:

from threading import Thread,Lock
from queue import Queue
import time



class myThread(Thread):
    def __init__(self,name,q):
        super().__init__()
        self.name= name
        self.q = q

    def run(self):
        print(f'{self.name}在運行')
        task(self.name,self.q)
        print(f'{self.name}退出')

def task(name,tq):

    q_lock.acquire()
    print(q.empty())
    if not q.empty():
        print(f'{name}'+tq.get())
        q_lock.release()
    else:
        q_lock.release()
    time.sleep(1)



thread_list = ['線程-','線程二','線程三','線程四','線程五']
threads =[]
q = Queue(10)
q_lock = Lock()

for threaName in thread_list:
    thread=myThread(threaName,q)
    thread.start()
    threads.append(thread)

q_lock.acquire()
for i in range(5,10):
    q.put('data'+str(i))
q_lock.release()

while not q.empty():
    pass

for thread in thread_list:
    thread.join()

運行結果如下:

 

 

好了 ,今天就複習到這裏,明天使用多線程爬取豆瓣TOP250 

 

加油

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章