1. 程式人生 > >python基礎之執行緒

python基礎之執行緒

通過重寫run呼叫執行緒:

import threading
def handle(sid):
    print("Thread %d run"%sid,threading.current_thread())

class MyThread(threading.Thread):
    def __init__(self,sid):
        threading.Thread.__init__(self)
        self.sid=sid
    def run(self):
        handle(self.sid)

for i in range(1,11):
    t=MyThread(i)
    t.start()
    t.join()

執行緒同步之訊號量控制實現:

semaphore=threading.Semaphore(0)#先生產再消費,item預設初值可以不用設定
semaphore=threading.BoundedSemaphore(1)#先消費再生產,再消費。item必須要有預設初值

通過acquire鎖住執行緒,通過release解鎖執行緒。

import threading
import time
import random
# semaphore=threading.Semaphore(0)#先生產再消費,item預設初值可以不用設定
semaphore=threading.BoundedSemaphore(1)#先消費再生產,再消費。item必須要有預設初值

def consumer():
    print("掛起:")
    semaphore.acquire()
    print("Consumer:消費%s."%item)

def producer():
    global item
    item=1000
    time.sleep(1)
    item=random.randint(1,1000)
    print("producer:生產%s."%item)
    semaphore.release()

threads=[]
for i in range(0,2):
    t2=threading.Thread(target=consumer)
    t1=threading.Thread(target=producer)
    t1.start()
    t2.start()
    threads.append(t1)
    threads.append(t1)
for t in threads:
    t.join()

執行緒同步之事件機制實現:

import queue

通過queue.Queue()的wait、set、clear實現

import queue
from random import randint
from threading import Thread
from threading import Event

class  WriteThread(Thread):
    def __init__(self,q,WE,RE):
        super().__init__()
        self.queue=q
        self.RE=RE
        self.WE=WE
    def run(self):
        data=[randint(1,10) for _ in range(0,5)]
        self.queue.put(data)
        print("WT,寫入RT完畢{0}".format(data))
        self.RE.set()
        print("WT,通知RT執行緒")
        self.WE.wait()
        print("WT,寫入事件完畢")
        self.WE.clear()
        print("WT,清理完畢")

class ReadThread(Thread):
    def __init__(self,q,WE,RE):
        super().__init__()
        self.queue=q
        self.RE=RE
        self.WE=WE
    def run(self):
        while True:
            self.RE.wait()
            print("RT,讀取等待")
            data=self.queue.get()
            print("RT,讀取WE資料{0}".format(data))
            self.WE.set()
            print("RT,傳送寫事件")
            self.RE.clear()
            print("RT,清理完畢")

q=queue.Queue()
WE=Event()
RE=Event()
writethread=WriteThread(q,WE,RE)
readthread=ReadThread(q,WE,RE)

writethread.start()
readthread.start()

執行緒同步之條件鎖實現:

from threading import Condition

c=Condition

通過c.acquire()鎖住資源,c.release()釋放資源

from threading import Thread
from threading import Condition
import time
import random

c=Condition()
itemNum=0
item=0
def consumer():
    global item
    global itemNum
    c.acquire()#鎖住資源
    while 0==itemNum:
        print("Consumer:掛起")
        c.wait()#等待
    itemNum-=1
    print("Consumer:消費%s"%item,itemNum)
    c.release()#釋放資源

def producer():
    global item
    global itemNum
    time.sleep(1)
    c.acquire()
    item=random.randint(1,1000)
    itemNum+=1
    print("Producer:生產%s"%item)
    c.notifyAll()#喚起所有執行緒,放置執行緒永遠處理沉默狀態
    # c.notify()#換起被wait掛起的執行緒
    c.release()

threads=[]
for i in range(0,3):
    t1=Thread(target=producer)
    t2=Thread(target=consumer)
    t1.start()
    t2.start()
    threads.append(t1)
    threads.append(t2)

for t in threads:
    t.join()#等待所有執行緒完成

通過定時器實現輪動(持續列印):

threading.Timer(1,func)
import threading
import time
def loop_timer_headle():
    print('Timer Headle!')
    global timer2
    timer2=threading.Timer(1,loop_timer_headle)#建立定時器
    timer2.start()
timer2=threading.Timer(1,loop_timer_headle)#建立定時器
timer2.start()
time.sleep(10)
timer2.cancel()#結束定時器

通過submit和map分別實現搶佔執行緒池和非搶佔執行緒池:

from concurrent.futures import ThreadPoolExecutor
import time

def printperson(p):
    print(p)
    time.sleep(1)
person=['Student','Teacher','Monther','Father','Son']
#建立搶佔執行緒池
start1=time.time()
with ThreadPoolExecutor(len(person)) as executor:
    for i in person:
        executor.submit(printperson,i)
end1=time.time()
print("time1:"+str(end1-start1))

#非搶佔執行緒池
start2=time.time()
with ThreadPoolExecutor(len(person)) as executor:
    executor.map(printperson,person)
end2=time.time()
print("time2:"+str(end2-start2))