python基础之线程

最常用的多线程实现方式是通过重载Run实现,简单例子如下:

import threading
import time
import random

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必须要有默认初值
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()

通过事件机制实现线程同步,from threading import Event,Event中有set设置事件、wait等待事件、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,acquire()锁住资源,wait()等待资源,notify唤起被wait等待的资源,notifyAll唤起所有线程,防止线程永远处于沉默在状态,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()#等待所有线程完成

线程池,通过concurrent.future模块下的ThreadPoolExecutor实现。

"""线程池"""

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值