0
点赞
收藏
分享

微信扫一扫

多线程与并发、并行的区别及其应用

承蒙不弃 2024-07-24 阅读 25

本套课在线学习视频(网盘地址,保存到网盘即可免费观看):

https://pan.quark.cn/s/677661ea63b3

多线程是计算机科学中的一个重要概念,用于实现程序的并发执行。本文将详细介绍多线程的基本概念,区分并行和并发两种执行方式,并讨论在Python中如何处理CPU密集型和IO密集型任务。

00:00 - 多线程与并行、并发的区别及其应用

并行与并发的区别

  • 并行:在同一时刻多个程序或操作同时运行,需要多CPU支持。
  • 并发:在同一时间段内,多个程序或操作交替执行,但CPU需要频繁地在它们之间切换。

多线程的应用

多线程适用于并发执行,特别是在IO密集型任务中,可以显著提高效率。

02:28 - 理解Python中的并发与IO密集型任务

CPU密集型任务

CPU密集型任务需要持续占用CPU资源,不适合使用多线程。

IO密集型任务

IO密集型任务如网络请求,CPU大部分时间处于空闲状态,可借助多线程提高效率。

Python中的多线程

尽管Python的CPython解释器因GIL存在无法实现真正的并行计算,但对于IO密集型任务,通过多线程仍能显著提升效率。

多进程与多线程

在需要大量计算时,多线程可能不再适用,此时应转向多进程以发挥CPU多核优势。

代码示例

多线程示例:IO密集型任务

import threading
import time

def io_bound_task(task_id):
    print(f"Task {task_id} started")
    time.sleep(2)  # Simulate IO-bound task
    print(f"Task {task_id} completed")

threads = []
for i in range(5):
    thread = threading.Thread(target=io_bound_task, args=(i,))
    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()

多进程示例:CPU密集型任务

import multiprocessing
import time

def cpu_bound_task(task_id):
    print(f"Task {task_id} started")
    result = 0
    for i in range(10**7):
        result += i
    print(f"Task {task_id} completed")

processes = []
for i in range(5):
    process = multiprocessing.Process(target=cpu_bound_task, args=(i,))
    processes.append(process)
    process.start()

for process in processes:
    process.join()

综合示例:混合使用多线程和多进程

import threading
import multiprocessing
import time

def io_bound_task(task_id):
    print(f"IO Task {task_id} started")
    time.sleep(2)  # Simulate IO-bound task
    print(f"IO Task {task_id} completed")

def cpu_bound_task(task_id):
    print(f"CPU Task {task_id} started")
    result = 0
    for i in range(10**7):
        result += i
    print(f"CPU Task {task_id} completed")

# Using threading for IO-bound tasks
io_threads = []
for i in range(5):
    thread = threading.Thread(target=io_bound_task, args=(i,))
    io_threads.append(thread)
    thread.start()

for thread in io_threads:
    thread.join()

# Using multiprocessing for CPU-bound tasks
cpu_processes = []
for i in range(5):
    process = multiprocessing.Process(target=cpu_bound_task, args=(i,))
    cpu_processes.append(process)
    process.start()

for process in cpu_processes:
    process.join()

通过这些示例代码,您可以更好地理解如何在Python中使用多线程和多进程处理不同类型的任务,从而提高程序的执行效率。

举报

相关推荐

0 条评论