python線程+隊列(queue)

---恢復內容開始---python

python的線程學習安全

用處 
pocpiliang腳本的編寫

函數式:調用 _thread 模塊中的start_new_thread()函數來產生新線程。語法以下:多線程

_thread.start_new_thread ( function, args[, kwargs] )

參數說明:app

  • function - 線程函數。
  • args - 傳遞給線程函數的參數,他必須是個tuple類型。
  • kwargs - 可選參數。
import _thread
import time
爲線程定義一個函數
def print_time(threadName,delay):
    i=0
    while i<5:
        time.sleep(delay)
        i=i+1
        print("%s,%s"%(threadName,time.ctime(time.time())))
try:
_thread.start_new_thread(print_time,("first",2,))
_thread.start_new_thread(print_time,("second",4,))
except:
    print("太快了")

咱們能夠看見 這個線i<5發送四次包 first發兩次  second發一次函數

 

線程模塊

Python3 經過兩個標準庫 _thread 和 threading 提供對線程的支持。

_thread 提供了低級別的、原始的線程以及一個簡單的鎖,它相比於 threading 模塊的功能仍是比較有限的。

threading 模塊除了包含 _thread 模塊中的全部方法外,還提供的其餘方法:

    threading.currentThread(): 返回當前的線程變量。
    threading.enumerate(): 返回一個包含正在運行的線程的list。正在運行指線程啓動後、結束前,不包括啓動前和終止後的線程。
    threading.activeCount(): 返回正在運行的線程數量,與len(threading.enumerate())有相同的結果。

除了使用方法外,線程模塊一樣提供了Thread類來處理線程,Thread類提供瞭如下方法:

    run(): 用以表示線程活動的方法。
    start():啓動線程活動。

    join([time]): 等待至線程停止。這阻塞調用線程直至線程的join() 方法被調用停止-正常退出或者拋出未處理的異常-或者是可選的超時發生。
    isAlive(): 返回線程是否活動的。
    getName(): 返回線程名。
    setName(): 設置線程名。
import threading
import time
class myThread(threading.Thread):
    def __init__(self,threadID,name,counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name =name
        self.counter =counter
    def run(self):
        print("開始線程"+self.name)
        print_time(self.name,self.counter,5)
        print("退出線程"+self.name)
def print_time(threadName,delay,counter):
    while counter>0:
        time.sleep(delay)
        print("%s: %s" % (threadName, time.ctime(time.time())))
        counter=counter-1

#建立新線程
thread1 =myThread(1,"第一個線程",1)
thread2 =myThread(2,"第二個線程",2)

# 開啓新線程
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("退出主線程")

能夠看見這裏咱們調用線程學習

 

 

 

 那麼接下來重點來了ui

多線程

多線程的優點在於能夠同時運行多個任務(至少感受起來是這樣)。可是當線程須要共享數據時,可能存在數據不一樣步的問題。spa

考慮這樣一種狀況:一個列表裏全部元素都是0,線程"set"從後向前把全部元素改爲1,而線程"print"負責從前日後讀取列表並打印。線程

那麼,可能線程"set"開始改的時候,線程"print"便來打印列表了,輸出就成了一半0一半1,這就是數據的不一樣步。爲了不這種狀況,引入了鎖的概念。3d

import threading
import time

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("開啓線程: " + self.name)
        # 獲取鎖,用於線程同步
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        # 釋放鎖,開啓下一個線程
        threadLock.release()

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

threadLock = threading.Lock()
threads = []

# 建立新線程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# 開啓新線程
thread1.start()
thread2.start()

# 添加線程到線程列表
threads.append(thread1)
threads.append(thread2)

# 等待全部線程完成
for t in threads:
    t.join()
print ("退出主線程")

 

 

 能夠看見是先開始線程1而後線程一完了在開線程二

 

線程優先級隊列( Queue)

線程優先級隊列( Queue)

Python 的 Queue 模塊中提供了同步的、線程安全的隊列類,包括FIFO(先入先出)隊列Queue,LIFO(後入先出)隊列LifoQueue,和優先級隊列 PriorityQueue。

這些隊列都實現了鎖原語,可以在多線程中直接使用,可使用隊列來實現線程間的同步。

Queue 模塊中的經常使用方法:

    Queue.qsize() 返回隊列的大小
    Queue.empty() 若是隊列爲空,返回True,反之False
    Queue.full() 若是隊列滿了,返回True,反之False
    Queue.full 與 maxsize 大小對應
    Queue.get([block[, timeout]])獲取隊列,timeout等待時間
    Queue.get_nowait() 至關Queue.get(False)
    Queue.put(item) 寫入隊列,timeout等待時間
    Queue.put_nowait(item) 至關Queue.put(item, False)
    Queue.task_done() 在完成一項工做以後,Queue.task_done()函數向任務已經完成的隊列發送一個信號
    Queue.join() 實際上意味着等到隊列爲空,再執行別的操做

 隊列1 單向先進先出隊列

import queue
#單向隊列
q = queue.Queue(5)
print(q.maxsize)
for i in range(4):
    q.put(i)
print(q.get())
print(q.qsize())
#先進後出隊列

 

 此時q.get()從隊列裏面取出來的是0 q.qsize還剩3個因此輸出3

若是代碼改爲

import queue
#單向隊列
q = queue.Queue(5)
print(q.maxsize)
for i in range(4):
    q.put(i)
    print(q.get())
print(q.qsize())
#先進後出隊列

 那麼將輸出  進一個出一個 那麼隊列爲空 q.qsize爲0

 

 接下來是先進後出隊列

import queue
q =queue.LifoQueue()
for i in range(5):
    q.put(i)
print(q.get())
print(q.qsize())

那麼看看運行效果

 

 和咱們預想的同樣

接下來是優先級隊列的講解

import queue
q =queue.PriorityQueue()
q.put((5, 5454))
q.put((5, 532566))
q.put((3, 555))
q.put((7, 344))
print(q.get())
print(q.get())

優先級隊列put進去的是一個元祖,(優先級,數據),優先級數字越小,優先級越高 話很少說咱們看代碼

若是有兩個元素優先級是同樣的,那麼在出隊的時候是按照先進先出的順序的。

 

 接下來是雙端隊列的講解 看代碼

import queue
q =queue.deque()
for i in range(3):
    q.append(i) 尾部加入
for c in range(5,8):
    q.appendleft(c) 首部加入
q.insert(2,"我是二號位") 任意位置插入
for i in range(10):
    print(q.pop()) 從尾部出

 

相關文章
相關標籤/搜索