欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python多线程的适用场景

程序员文章站 2022-07-12 11:19:48
...

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()