python实现并发

1.多线程

# -*- coding: utf-8 -*-
import threading
import time


def print_hello_world():
    print("hello-world")


def concurrent_hello_world(n):
    threads = []
    # 记录开始时间
    start_time = time.time()

    # 创建并启动多个线程
    for _ in range(n):
        thread = threading.Thread(target=print_hello_world)
        threads.append(thread)
        thread.start()

    # 等待所有线程执行完毕
    for thread in threads:
        thread.join()

    # 记录结束时间
    end_time = time.time()
    print(f"Total time taken: {end_time - start_time:.6f} seconds")


concurrent_hello_world(10)

2.线程池

# -*- coding: utf-8 -*-
import time
from concurrent.futures import ThreadPoolExecutor


def print_hello_world():
    print("hello-world")


def concurrent_hello_world(n):
    # 记录开始时间
    start_time = time.time()

    with ThreadPoolExecutor(max_workers=n) as executor:
        # 提交多次打印任务并等待任务完成
        executor.map(lambda _: print_hello_world(), range(n))

    # 记录结束时间
    end_time = time.time()
    print(f"Total time taken: {end_time - start_time:.6f} seconds")


concurrent_hello_world(10)

3.异步任务

# -*- coding: utf-8 -*-
import asyncio
import time


async def print_hello_world():
    print("hello-world")


async def concurrent_hello_world(n):
    # 记录开始时间
    start_time = time.time()

    # 并发执行多个异步任务
    tasks = [print_hello_world() for _ in range(n)]
    await asyncio.gather(*tasks)

    # 记录结束时间
    end_time = time.time()
    print(f"Total time taken: {end_time - start_time:.6f} seconds")


# 运行异步任务
asyncio.run(concurrent_hello_world(10))

posted @ 2024-10-20 21:39  tt_贝塔  阅读(0)  评论(0编辑  收藏  举报