计算密集型任务:任务数=cpu核数,C更适合
计算量很大如计算圆周率和视频的高清解码,占用很多cpu计算资源;执行多任务时,任务过多则来回切换任务浪费时间,一般同时进行的任务数量应等于cpu核心数(os.cpu_count()查看),而c比python更适合。
IO密集型任务: 任务数尽量多,python更适合
IO速度远小于cpu和内存速度,因此IO操作占用cpu资源很少,如web应用和磁盘IO等IO密集型任务,大部分时间都在等待IO操作完成;在一定限度内,任务
越多则cpu的效率越高。脚本语言更适合,如python。
创建线程 Thread类:
threading.Thread(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None)
参数释义:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
*group* should be None; reserved for future extension when a ThreadGroup class is implemented. *target* is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called. *name* is the thread name. By default, a unique name is constructed of the form "Thread-N" where N is a small decimal number. *args* is the argument tuple for the target invocation. Defaults to (). *kwargs* is a dictionary of keyword arguments for the target invocation. Defaults to {}. If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.
target = 可调用对象名称
name = 线程名称,默认为 ‘Thread-N’
args = 传给target的参数,注意是元组
Thread对象方法:
start()----->run()
start()表示启动线程活动,该方法在每个线程对象中最多被调用一次。调用start()后,线程对象再自动调用run()方法,正式运行线程活动。
第一,若Thread仅实例化而没有子类化,则该线程对象启动后的线程活动为:target(*args,*kwargs)
第二,另一种指定线程活动的方式就是在子类中重写__init__()和run()方法,其它方法不能重写
join(timeout=None)
等待直到线程终止,只有等调用join()的线程终止后才能调用线程。此方法不是必须的,如果其它线程有其它事要做,就不必设置;只有需要等待线程结束的时候才要调用该方法
threading方法:
current_thread()或currentThread() 返回当前线程对象
active_count()或activeCount() 返回当前活着的线程对象数量
enumerate() 返回当前所有活着的线程对象的列表
main_thread() 返回主线程对象
setDaemon(daemonic=False)
设置守护线程(必须在调用start()前设置),参数为True表示设置该线程为守护线程,因为主线程不是守护线程,因此主线程创建的所有线程都默认为非守护线程。
表示当所有非守护线程运行结束,程序就退出,而不用等待守护线程结束。
threading.Lock()对象方法:
acquire() 获得lock
release() 释放lock,其它线程才能获得lock
threading.local()对象:
在主线程中创建ThreadingLocal对象或local子类的对象,并在上面存储属性;它相对于其它线程是全局变量,该对象在主线程及各其它线程中存储各自的数据,而互不影响
线程间通信:queue模块
queue.Queue() 先进先出类对象
Queue.put(item,block=True,timeout=None) 将item放入队列,阻塞调用无超时
Queue.get(block=True,timeout=None) 从队列中移除并返回一个数据,阻塞调用,直到有数据可用