python多线程

首页 » 线/进程 » python多线程

一、类实现多线程

import threading
import time
class me(threading.Thread):#继承
    def run(self):#重写
        for i in range(10):
            print("9--")
            time.sleep(1)
list=[]
for i in range(3):
    t=me()#初始化
    t.start()#开启
    list.append(t)
for i in list:
    t.join()#主线程等待子线程执行完成,不需要阻塞
# while(True): #阻塞
#     pass
print("over")

二、condition

import threading
import time
def go1():
    with cond:
        for i in range(10):
            time.sleep(1)
            print(threading.current_thread().name,i)
            if i==5:
                cond.wait()#等待
def go2():
    with cond:
        for i in range(10):
            time.sleep(1)
            print(threading.current_thread().name, i)

        cond.notify()#通知
cond=threading.Condition()#线程条件变量   兼顾同步和通信
threading.Thread(target=go1).start()
threading.Thread(target=go2).start()

三、独立空间

import threading
data=threading.local()#每个线程独立存储空间 独立变量
t1=lambda x:x+1
t2=lambda x:x+"1"
def pd(func,x):
    data.x=x
    print(id(data))
    for i in range(5):
        data.x=func(data.x)
        print(threading.current_thread().name,data.x)
threading.Thread(target=pd,args=(t1,1)).start()
threading.Thread(target=pd,args=(t1,"1")).start()

四、信号量

import threading
import time
sem=threading.Semaphore(3)#限制线程的最大数值
def go():
    with sem:#锁定数量
        for i in range(10):
            print(threading.current_thread().name,i)
            time.sleep(1)
for j in range(5):
    threading.Thread(target=go).start()

五、生产者消费者

import threading
import queue
import time
import random
class create(threading.Thread):
    def __init__(self,index,queue):
        threading.Thread.__init__(self)
        self.index=index
        self.queue=queue
    def run(self):
        while(True):
            time.sleep(3)
            num=random.randint(0,10000)
            self.queue.put(str(num))
            print("input "+str(self.index)+" 生产 "+str(num))
class xiaofei(threading.Thread):
    def __init__(self,index,queue):
        threading.Thread.__init__(self)
        self.index=index
        self.queue=queue
    def run(self):
        while True:
            time.sleep(1)
            if self.queue.get() is None:
                break
            print("客户",self.index,"物品",self.queue.get())
myqueue=queue.Queue(10)
for i in range(3):
    create(i,myqueue).start()
for i in range(8):
    xiaofei(i,myqueue).start()

六、线程池

import time
import threadpool
def show(str):
    print(str)
    time.sleep(2)
namelist=[1,2,3,4]
pool=threadpool.ThreadPool(10)
req=threadpool.makeRequests(show,namelist)# 请求列表
for re in req:
    pool.putRequest(re)#依次处理请求列表

七、线程调度

import threading
import time
def go1():
    with cond:
        for i in range(1,10,2):
            time.sleep(1)
            print(threading.current_thread().name,i)
            cond.notify()
            cond.wait()
def go2():
    with cond:
        for i in range(0,10,2):
            time.sleep(1)
            print(threading.current_thread().name, i)
            cond.wait()
            cond.notify()#通知
cond=threading.Condition()#线程条件变量
threading.Thread(target=go2).start()
threading.Thread(target=go1).start()

八、线程通信

import threading
import time


def g():
    e = threading.Event()  # 事件

    def go():
        for i in range(10):
            e.wait()  # 等待 直到set
            e.clear()
            print("*",i)

    threading.Thread(target=go).start()
    return e


t = g()
for j in range(10):
    time.sleep(j)
    t.set()  # 激发事件

九、线程锁

import threading
import time
num=0
lock=threading.Lock()#创建一个锁
# lock=threading.RLock()#避免单线程死锁
class me(threading.Thread):#继承
    def run(self):#重写
        global num
        # with lock:自动释放
        if lock.acquire(1):#锁住成功,没有锁住就一直等待,也就是获得锁,1代表独占
            for i in range(1000000):
                num+=1
            lock.release()#释放锁
        print(num)
list=[]
for i in range(3):
    t=me()#初始化
    t.start()#开启
    list.append(t)
for i in list:
    t.join()#主线程等待子线程执行完成,不需要阻塞
print("over")

十、匹配线程数量

import time
import threading
bar=threading.Barrier(3)#必须凑两个线程,才能一起执行
def go():
    for i in range(10):
        print(threading.current_thread().name,i)
        time.sleep(5)
        bar.wait()
        print("dddd"+threading.current_thread().name, i)
for j in range(4):
    threading.Thread(target=go).start()

十一、csv读

import csv
path=r"/Users/new/lean/test/docter/doctor2.csv"
read=csv.reader(open(path,"r"))
for i in read:
    print(i)

十二、csv写

import csv
with open("1.csv","w",newline="") as da:
    cs=csv.writer(da,dialect=("excel"))
    cs.writerow([1,2,3,4,5])
    cs.writerow([1, 2, 3, 4, 5])
分享到:
赞(0) 打赏

评论 2

评论前必须登录!

 

  1. #1

    可以

    努力8个月前 (03-27)
  2. #2

    我也是小白以后多多交流

    渣渣辉8个月前 (03-28)

觉得文章有用就打赏一下弟弟吧

支付宝扫一扫打赏

微信扫一扫打赏

Vieu4.5主题
专业打造轻量级个人企业风格博客主题!专注于前端开发,全站响应式布局自适应模板。
正在播放:

作者想对您说:

累了就停下来听首歌吧

听完后会给您一个好心情

最后

等到您不容易

还希望您能多待一会儿

      00:00/00:00