11-多线程的简单使用

  • 阅读: 652
  • 更新: 2022-06-30

多线程适合处理 I/O 密集型任务;计算/CPU 密集型任务需要使用多进程
多线程中使用全局变量,需要是线程安全的。可使用 Queue 标准库;另外 list.append() 操作也是线程安全的
https://docs.python.org/zh-cn/3/library/threading.html

1. 代码示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import threading
import time


def _get_info_thread(thread_id):
    print(f'当前线程{thread_id}')
    time.sleep(1)


threads = []
for _id in range(10):
    t = threading.Thread(
        target=_get_info_thread,  # 线程调用的函数
        args=(_id,)  # args 是元组类型,当只有一个参数时,需要加个逗号
    )
    t.start()  # 启动线程
    threads.append(t)
for th in threads:
    th.join()  # 等待线程执行完成

运行结果可发现总体仅耗时1秒,而不是10秒


=== 全文完 ===


欢迎加入QQ群:855013471

京公网安备 11011302003970号 京ICP备2022012301号-1