Python 线程

1、Python 中的线程是通过 threading 模块来实现的,线程允许你在 Python 程序中并发执行多个任务

  1. 线程:

    • 线程是最小的可调度执行单元。
    • 每个线程都有自己的执行栈和程序计数器,但共享同一进程的内存空间。
  2. 线程调度:

    • 线程的调度由操作系统管理。
    • 线程可以在多核处理器上并行执行。
  3. 全局解释器锁 (GIL):

    • Python 的 C 实现(CPython)包含一个全局解释器锁(GIL),它确保任何时候只有一个线程在执行 Python 字节码。
    • GIL 的存在意味着即使在多线程程序中,CPU 密集型任务也难以实现真正的并行执行。
  4. 线程安全:

    • 当多个线程访问共享资源时,需要使用锁来确保数据的一致性。
    • threading.Lock() 和 threading.RLock() 是常用的锁类型。
import threading
import time

def task(name, delay):
    print(f"Task {name} starts.")
    time.sleep(delay)
    print(f"Task {name} finishes.")

def main():
    # 创建并启动两个任务
    thread1 = threading.Thread(target=task, args=("Task 1", 2))
    thread2 = threading.Thread(target=task, args=("Task 2", 1))
    
    thread1.start()
    thread2.start()
    
    # 等待所有任务完成
    thread1.join()
    thread2.join()

if __name__ == "__main__":
    main()

 当多个线程需要访问共享资源时,使用锁来确保数据的一致性

import threading
import time

# 共享变量
counter = 0

# 锁对象
lock = threading.Lock()

def increment_counter(n):
    global counter
    with lock:
        for _ in range(n):
            counter += 1
            time.sleep(0.01)  # 模拟 I/O 操作
    print(f"Counter incremented to {counter}")

def main():
    # 线程数量
    num_threads = 5
    
    # 创建并启动线程
    threads = []
    for _ in range(num_threads):
        thread = threading.Thread(target=increment_counter, args=(100,))
        thread.start()
        threads.append(thread)
    
    # 等待所有线程完成
    for thread in threads:
        thread.join()

    print(f"Final counter value: {counter}")

if __name__ == "__main__":
    main()

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值