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))

猜你喜欢

转载自blog.csdn.net/zx520113/article/details/83928861