在Python中,由于全局解释器锁(GIL)的存在,多线程并不能真正并行执行Python代码,但是它们可以用于I/O密集型任务,如文件读写、网络通信等。
创建线程 |
线程方法 |
||
● _thread模块 |
_thread.start_new_thread ( function, args[, kwargs] ) |
||
threading 模块 |
比_thread模块多出的方法: ● threading. current_thread(): 返回当前的线程变量。 ● threading.enumerate(): 返回一个包含正在运行的线程的列表。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。 ● threading.active_count(): 返回正在运行的线程数量,与 len(threading.enumerate()) 有相同的结果。 ● threading.Thread(target, args=(), kwargs={}, daemon=None): |
||
1.使用 threading 模块创建线程 通过直接从 threading.Thread 继承创建一个新的子类,并实例化后调用 start() 方法启动新线程,即它调用了线程的 run() 方法: import threading class myThread (threading.Thread): def __init__(self, threadID, name, delay): threading.Thread.__init__(self)//必须的 def run(self): ..... # 创建新线程 thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread- |