线程
import threading
def my_function():
print("子线程开始执行")
# 创建并启动子线程
thread = threading.Thread(target=my_function)
thread.start()
# 打印当前存活的Thread对象数量
print("当前存活的Thread对象数量:", threading.active_count())
进程
from multiprocessing import Process, active_children
def my_function():
print("子进程开始执行")
# 创建并启动子进程
process = Process(target=my_function)
process.start()
# 获取当前存活的进程对象列表
process_list = active_children()
# 打印当前存活的进程对象数量
print("当前存活的进程对象数量:", len(process_list))
Python中的线程与进程并发编程示例
本文介绍了在Python中使用`threading`模块创建和启动子线程,以及`multiprocessing`模块处理子进程的基本操作。作者展示了如何计算当前活动线程和进程的数量。
2261

被折叠的 条评论
为什么被折叠?



