最近需要使用 python3 多线程处理大型数据,顺道探究了一下,python3 的线程模型的情况,下面进行简要记录;
多线程运行的优点:
- 使用线程可以把程序中占用时间较长的任务放到后台去处理;
- 用户界面可以更加吸引人,并且不阻塞界面的运行;
- 程序运行的速度可以更快;
- 充分利用CPU多核的特征进行处理;
内核线程:由操作系统内核创建和撤销;
用户线程:不需要内核支持在用户程序中实现的线程;
Python3 中的多线程:
- _thread 提供了一些原始的api 用于写多线程程序;
- threading 提供了更加便利的接口
- 两者都是python3内置的线程模块
#!/usr/bin/env python import _thread def print_time( threadName, delay): print (threadName) count = 0 while 1: pass count += 1 try: _thread.start_new_thread( print_time, ("Thread-1", 1, ) ) _thread.start_new_thread( print_time, ("Thread-2", 2, ) ) _thread.start_new_thread( print_time, ("Thread-3", 2, ) ) _thread.start_new_thread( print_time, ("Thread-4", 2, ) ) _thread.start_new_thread( print_time, ("Thread-5", 2, ) ) _thread.start_new_thread( print_time, ("Thread-6", 2, ) ) _thread.start_new_thread( print_time, ("Thread-7", 2, ) ) _thread.start_new_thread( print_time, ("Thread-8", 2, ) ) _thread.start_new_thread( print_time, ("Thread-9", 2, ) ) _thread.start_new_thread( print_time, ("Thread-10", 2, ) ) _thread.start_new_thread( print_time, ("Thread-11", 2, ) ) _thread.start_new_thread( print_time, ("Thread-12", 2, ) ) _thread.start_new_thread( print_time, ("Thread-13", 2, ) ) _thread.start_new_thread( print_time, ("Thread-14", 2, ) ) _thread.start_new_thread( print_time, ("Thread-15", 2, ) ) except: print ("Error: can't start thread!") while 1: pass