• 多线程使用


    关于 Python 中的多线程管理,以下是一些关键的注意事项和最佳实践:

    1、使用 threading 模块

    Python 的标准库 threading 模块是多线程编程的基础。可以通过以下方式创建和启动一个线程:

    import threading
    
    def thread_function(name):
        print(f"Thread {name} is running")
    
    thread = threading.Thread(target=thread_function, args=("Test",))
    thread.start()
    thread.join()  # 等待线程完成
    
    

    2、线程的终止

    Python 线程无法通过外部信号强制终止。通常的做法是使用一个线程内的标志来通知线程应该退出:

    import threading
    import time
    
    exit_flag = False
    
    def thread_function():
        global exit_flag
        while not exit_flag:
            print("Thread is running")
            time.sleep(1)
    
    thread = threading.Thread(target=thread_function)
    thread.start()
    
    # 让线程运行几秒钟
    time.sleep(5)
    exit_flag = True
    thread.join()  # 等待线程完成
    
    

    3、守护线程

    守护线程会在主程序退出时自动终止。可以通过设置 daemon 属性来创建守护线程:

    thread = threading.Thread(target=thread_function)
    thread.daemon = True  # 设置为守护线程
    thread.start()
    
    

    4、使用 concurrent.futures 模块

    对于更高级的线程管理,可以使用 concurrent.futures.ThreadPoolExecutor,它提供了更简洁的接口:

    from concurrent.futures import ThreadPoolExecutor
    
    def thread_function(name):
        print(f"Thread {name} is running")
    
    with ThreadPoolExecutor(max_workers=5) as executor:
        futures = [executor.submit(thread_function, i) for i in range(5)]
    
    # 等待所有线程完成
    for future in futures:
        future.result()
    
    

    5、锁和同步

    在多线程环境中,多个线程可能会同时访问和修改同一个资源,导致数据竞争。可以使用 threading.Lock 来避免此类问题:

    lock = threading.Lock()
    
    def thread_function():
        with lock:
            # 进行需要同步的操作
            print("Thread is running")
    
    thread = threading.Thread(target=thread_function)
    thread.start()
    thread.join()
    
    
  • 相关阅读:
    vue+elementUI 设置el-descriptions固定长度并对齐
    Springboot引入jasypt实现加解密
    微信小程序阻止返回事件
    自动化运维?看看Python怎样完成自动任务调度
    Java 近期新闻:JDK 19 进入 RDP2、Oracle 关键补丁更新、TornadoVM on M1、Grails CVE
    如何使用 Yolov4 训练人脸口罩检测模型
    Ehcache配置资料,方便自己查
    Spring 常用注解及作用
    【Leetcode】202. 两数之和
    基于若依springboot架构实现数据多维统计
  • 原文地址:https://blog.csdn.net/weixin_40400335/article/details/139821815