线程、进程、线程池、进程池简单思路

1.多线程

from threading import Thread

示例1
from threading import Thread

def func1(name):
    for i in range(1000):
        print("func1", i)

def func2(name):
	for i in range(1000):
        print("func2", i)
        
if __name__ == "__main__": # args 传递参数, 元组
    t1 = Thread(target=func1, args=("测试",))
    t1.start()
    t2 = Thread(target=func2, args=("测试",))
    t2.start()
示例2
from threading import Thread

class MyThread(Thread):
    def run(self): # 固定的
        for i in range(1000):
            print("子", i)


# 构造函数传参
if __name__ == "__main__":
    t = MyThread()
    t.start() # 默认执行run
    for i in range(1000):
        print("主", i)

2.多进程

from multiprocessing import Process

from multiprocessing import Process

def func():
    for i in range(1000):
        print("子进程", i)

 if __name__ == "__main__":
    p = Process(target=func)
    p.start()
    for i in range(1000):
        print("主进程", i)

3.线程池

一次性开辟一些线程, 用户直接给线程池提交任务。线程任务的调度交给线程池来完成

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

def fun(name):
    for i in range(1000):
        print(name, i)
if __name__ == "__main__":
    # 
    with ThreadPoolExecutor(50) as t: # 创建线程池, 50 个线程
        for i in range(100):
            t.submit(fun, name=f"线程{i}")
    # 等线程池中的任务结束,才执行
    print("结束")
        

4.进程池( 与线程池只修改了 with 后的类名)

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

def fun(name):
    for i in range(1000):
        print(name, i)
if __name__ == "__main__":
    # 
    with ProcessPoolExecutor(50) as t: # 创建进程池, 50 个线程
        for i in range(100):
            t.submit(fun, name=f"进程{i}")
    # 等线程池中的任务结束,才执行
    print("结束")

5.异步协程 aiohttp

posted @ 2021-03-25 20:18  ShanCe-刘勇  阅读(50)  评论(0编辑  收藏  举报