python多线程和线程池,多进程和进程池

Python3.12之前因为GIL的限制,CPU没有真正的多线程,使用threading不过是提高了I/O密集型运算的速度

多线程

import time
import threading


def my_function(seconds):
    time.sleep(seconds)


start_time = time.perf_counter()
thread1 = threading.Thread(target=my_function, args=[1])
thread2 = threading.Thread(target=my_function, args=[1])
thread1.start()
thread2.start()
thread1.join()
thread2.join()
finish_time = time.perf_counter()
print("Finished in {} seconds".format(finish_time - start_time))

线程池

import time
import concurrent.futures


def my_function(seconds):
    time.sleep(seconds)
    return f"完成睡眠{seconds}"


start_time = time.perf_counter()
with concurrent.futures.ThreadPoolExecutor() as executor:
    futures = [executor.submit(my_function, 1) for _ in range(10)]
    for future in concurrent.futures.as_completed(futures):
        print(future.result())
finish_time = time.perf_counter()
print("Finished in {} seconds".format(finish_time - start_time))

如果需要提高CPU并发的速度,推荐使用多进程

多进程,注意要加上if name == ‘main’:,否则代码会从上往下执行,重复创建进程

import time
import concurrent.futures
import multiprocessing


def my_function(seconds):
    time.sleep(seconds)

if __name__ == '__main__':
    start_time = time.perf_counter()
    p1 = multiprocessing.Process(target=my_function, args=[1])
    p2 = multiprocessing.Process(target=my_function, args=[1])
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    finish_time = time.perf_counter()
    print("Finished in {} seconds".format(finish_time - start_time))

进程池

import time
import concurrent.futures
import multiprocessing


def my_function(seconds):
    time.sleep(seconds)
    return f"睡眠{seconds}秒"

if __name__ == '__main__':
    start_time = time.perf_counter()
    with concurrent.futures.ProcessPoolExecutor() as executor:
        futures = [executor.submit(my_function, 1) for _ in range(10)]
        for future in concurrent.futures.as_completed(futures):
            print(future.result())
    finish_time = time.perf_counter()
    print("Finished in {} seconds".format(finish_time - start_time))
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值