当前位置:首页>python>第5期. Python的线程介绍

第5期. Python的线程介绍

  • 2026-10-13 05:13:21
第5期. Python的线程介绍
点击蓝字   
关注我们

【学点python · 今日知识点】你好呀~这里是专注python咨询和信息”的小课堂📚今天用3分钟,带你了解 Python线程 (本期主题)✅ 适合:Python爱好者 / 程序开发者 / 转行学习者/其它✅ 收藏本文,随时回看不迷路~👇 读完有收获?欢迎留言“已学”打卡!

正文

一、线程基础概念

  • 定义与特性
    线程是操作系统调度的最小单位,共享进程的内存空间,创建开销小(约1-5微秒),但一个线程崩溃可能导致整个进程终止。

    Definition & Characteristics: A thread is the smallest unit of scheduling by the operating system. It shares the memory space of the process, has a low creation overhead (approx. 1-5 microseconds), but the crash of one thread can cause the termination of the entire process.

  • 与进程的区别
    进程拥有独立内存空间,资源隔离性强,但创建开销大(约100微秒-1毫秒);线程更适合频繁通信和共享数据的场景。

    Difference from Processes: Processes have independent memory spaces and strong resource isolation, but a higher creation overhead (approx. 100 microseconds - 1 millisecond). Threads are more suitable for scenarios requiring frequent communication and shared data.

二、线程创建方式

1.函数传递方式
通过Thread(target=函数, args=参数)创建,需调用start()启动线程。

Function Passing Method: Created via Thread(target=function, args=arguments). Requires calling start() to launch the thread.

import threadingdef worker(name):    print(f"线程 {name} 执行")    # print(f"Thread {name} is executing")t = threading.Thread(target=worker, args=("Worker-1",))t.start()
2.继承Thread类
重写run()方法定义线程行为。

Inheriting the Thread Class: Define thread behavior by overriding the run() method.

class MyThread(threading.Thread):    def run(self):        print("自定义线程执行")        # print("Custom thread is executing")t = MyThread()t.start()

三、核心操作与同步

  • 线程控制

Thread Control:

    • join()
      :阻塞主线程等待子线程完成,需在所有线程启动后统一调用。

      join(): Blocks the main thread to wait for the child thread to complete. Should be called uniformly after all threads have started.

    • daemon
      属性:设为True时主线程退出则强制终止子线程,适用于后台任务。

      daemon attribute: If set to True, the child thread is forcibly terminated when the main thread exits. Suitable for background tasks.

  • 同步机制

Synchronization Mechanisms:

    • 锁(Lock)
      防止多线程竞争共享资源(如计数器),需用with lock:acquire()/release()管理。

      Lock: Prevents multiple threads from competing for shared resources (e.g., counters). Managed using with lock: or acquire()/release().

    • 条件变量(Condition)
      用于线程间协作(如生产者-消费者),支持wait()和notify()。

      Condition Variable: Used for inter-thread collaboration (e.g., producer-consumer). Supports wait() and notify().

    • 队列(Queue)
      线程安全的数据结构,自动处理锁和同步,推荐用于任务传递。

      Queue: A thread-safe data structure that automatically handles locking and synchronization. Recommended for task passing.

四、GIL的影响与场景选择

  • GIL机制
    Python的全局解释器锁导致同一时刻仅一个线程执行字节码,I/O密集型任务(如网络请求)中线程可释放GIL提升效率,而CPU密集型任务(如计算质数)需改用多进程。

    GIL Mechanism: Python's Global Interpreter Lock ensures only one thread executes bytecode at a time. In I/O-bound tasks (e.g., network requests), threads can release the GIL to improve efficiency. For CPU-bound tasks (e.g., calculating primes), multi-processing should be used instead.

  • 性能对比

Performance Comparison:

    • I/O密集型:多线程效率显著高于单线程(实测提升6-8倍)。

      I/O-bound: Multi-threading efficiency is significantly higher than single-threading (measured improvement of 6-8 times).

    • CPU密集型:多线程可能比单线程更慢,建议使用multiprocessing多进程。

      CPU-bound: Multi-threading might be slower than single-threading. It is recommended to use multiprocessing.

五、最佳实践

  1. 避免共享状态
    优先使用线程局部数据(threading.local())或不可变对象。

    Avoid Shared State: Prioritize using thread-local data (threading.local()) or immutable objects.

  2. 合理使用线程池
    通过concurrent.futures.ThreadPoolExecutor复用线程,减少创建开销。

    Use Thread Pools Wisely:Reusehreads via concurrent.futures.ThreadPoolExecutor to reduce creation overhead.

  3. 调试与监控
    使用threading.enumerate()查看活跃线程,current_thread().name标识线程用途。

    Debugging & Monitoring: Use threading.enumerate() to view active threads and current_thread().name to identify thread purposes.

注意:实际应用需结合任务类型选择线程或进程,警惕GIL对性能的影响,同步工具优先选用高级抽象(如Queue)以简化逻辑。

Note: In practical applications, choose between threads or processes based on the task type. Be wary of the performance impact of the GIL. Prioritize high-level abstractions (e.g., Queue) for synchronization to simplify logic.

点亮在看,你最好看!

💡 行动锦囊:✅ 收藏本文,实施时随时对照✅ 转发团队群,对齐认知少扯皮✅ 回复“OK”提前获取在线群聊二维码💌 你负责认真看,我们负责认真写关注【学点python】,让系统真正为你所用 ❤️


END

往期精彩回顾
第1期. PyQt5的窗口有哪些?(The categories of PyQt5 window)
第2期. PyQt5窗口怎么交互?
第3期. PyQt5怎么设置图标?How to set an icon in PyQt5?
第4期. PyQt5控件体系详解

最新文章

随机文章