• python多线程的适用场景


    1.多线程对于计算密集型无用

    需求:列表li1每个元素加1,列表li2每个元素加100
    # 导入模块
    import threading
    
    li1 = [11, 22, 33]  # +1
    li2 = [44, 55, 66]  # 100
    
    
    def func(data, plus):
        for i in range(len(data)):
            data[i] = data[i] + plus
    
    
    # 线程1:负责给li1每个元素加1
    t1 = threading.Thread(target=func, args=(li1, 1))
    t1.start()
    
    # 线程2:负责给li2每个元素加100
    t2 = threading.Thread(target=func, args=(li2, 100))
    t2.start()
    

    2.多线程对于IO操作有用

    # 导入模块
    import threading
    import uuid
    import requests
    
    # 图片地址列表
    url_list = [
        'https://www3.autoimg.cn/newsdfs/g28/M05/F9/98/120x90_0_autohomecar__ChsEnluQmUmARAhAAAFES6mpmTM281.jpg',
        'https://www2.autoimg.cn/newsdfs/g28/M09/FC/06/120x90_0_autohomecar__ChcCR1uQlD6AT4P3AAGRMJX7834274.jpg',
        'https://www2.autoimg.cn/newsdfs/g3/M00/C6/A9/120x90_0_autohomecar__ChsEkVuPsdqAQz3zAAEYvWuAspI061.jpg',
    ]
    
    
    def task(img_url):
        ret = requests.get(img_url)
        file_name = str(uuid.uuid4()) + '.jpg'
        with open(file_name, mode='wb') as f:
            f.write(ret.content)
    
    
    for url in url_list:
        t = threading.Thread(target=task, args=(url,))
        t.start()
    
  • 相关阅读:
    P1342 请柬
    P1186 玛丽卡
    Scala 中下划线的用法
    IDEA2017 maven Spark HelloWorld项目(本地断点调试)
    Spark内存管理详解
    Spark基础知识
    scala基本语法
    分布式锁的一点理解
    Redis并发问题
    redis集群原理
  • 原文地址:https://www.cnblogs.com/apollo1616/p/10350890.html
Copyright © 2020-2023  润新知