Python 中的线程与进程(四)
由于大多数程序不需要有多线程的能力,所以在Python启动的时候并不支持多线程。也就是说,Python中支持多线程所需要的数据结构特别是GIL并没有创建。当Python虚拟机启动的时候,多线程处理并没有打开,而仅仅支持单线程。只有当程序中使用了如thread.start_new_thread等方法的时候,python才知道需要有多线程处理的支持,此时,python虚拟机才会自动创建多线程处理所需要的数据结构与GIL。 生成和终止线程(由于thread模块比较低级,不被推荐使用,所以就不说了) 1 使用threading.Thread类(构造函数:Thread(group = None, target = None, name = None, args = (), kwargs = {}) 使用threading模块来创建线程是很简单的。简单地说,只要继承threading.Thread,然后在__init__方法中,调用threading.Thread类的__init__方法,重写类的run方法就可以了。 import threading class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): pass thread =