实现多线程多任务的步骤

步骤

 

1
2
3
4
5
6
1. 导入线程模块
import threading
2. 创建子线程并指定执行的任务
sub_thread = threading.Thread(target=任务名
3. 启动线程执行任务
sub_thread.start()

 

示例

复制代码
 1 '''
 2 在Python中,实现多线程多任务可以通过使用threading模块来创建和管理线程
 3 
 4 最佳实践:
 5     1. 使用适量的线程数:根据系统资源和任务需求,合理选择线程数量。过多的线程可能会导致资源竞争和性能问题。
 6     2. 确保线程安全:如果多个线程访问共享数据,要注意加锁或使用线程安全的数据结构来避免竞态条件。
 7     3. 避免阻塞操作:如果某个线程执行了长时间的阻塞操作,会影响其他线程的执行效率,因此应尽量避免阻塞操作,或使用非阻塞的替代方案。
 8     4. 异常处理:每个线程都应该有自己的异常处理机制,确保及时捕获和处理异常,避免线程退出导致整个程序崩溃。
 9 
10 常见的坑:
11     1. 全局解释器锁(GIL):Python的全局解释器锁限制了同一时间只能有一个线程执行Python字节码。这意味着在CPU密集型任务中,多线程可能无法提升性能。
12     2. 线程间通信:由于共享数据需要进行线程间同步,所以在多线程编程中需要小心处理数据共享和通信,以避免出现竞争条件和死锁。
13 '''
14 # 1. 导入线程模块
15 import threading
16 
17 
18 def task1():
19     thread_id = threading.get_ident() # 获取当前线程的id
20 print(f"Executing task 1,thread-id:{thread_id}") 21  # 执行任务1的代码 22 23 24 def task2(): 25 thread_id = threading.get_ident() 26 print(f"Executing task 2,thread-id:{thread_id}") 27  # 执行任务2的代码 28 29 30 def main(): 31 # 2. 创建线程并指定其任务 32 thread1 = threading.Thread(target=task1) 33 thread2 = threading.Thread(target=task2) 34 35 # 3. 启动线程 36  thread1.start() 37  thread2.start() 38 39  # 让主线程等待thread1、thread2的结束,此时主线程会阻塞在此,一直等待他们结束,才能继续执行 40  thread1.join() 41  thread2.join() 42 43 print("All tasks completed") 44 45 46 if __name__ == "__main__": 47 main()
复制代码

 

输出:

Executing task 1,thread-id:11020
Executing task 2,thread-id:3080
All tasks completed

 

posted @   Allen_Hao  阅读(113)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示