Python多线程是指通过并行执行多个线程来实现同时执行多个任务的编程技术。本文将从多个方面对Python多线程的两种写法进行详细阐述。
一、线程的创建和启动
1、通过继承Thread类来创建线程:
import threading class MyThread(threading.Thread): def run(self): print("线程启动成功") if __name__ == "__main__": t = MyThread() t.start()
2、通过实例化Thread类并传入可调用对象来创建线程:
import threading def my_func(): print("线程启动成功") if __name__ == "__main__": t = threading.Thread(target=my_func) t.start()
二、线程间的同步与通信
1、使用Lock进行线程同步:
import threading def worker(lock): lock.acquire() try: # 线程同步代码块 pass finally: lock.release() if __name__ == "__main__": lock = threading.Lock() t1 = threading.Thread(target=worker, args=(lock,)) t2 = threading.Thread(target=worker, args=(lock,)) t1.start() t2.start() t1.join() t2.join()
2、使用Event进行线程通信:
import threading def wait_for_event(event): print("等待事件触发") event.wait() print("事件已触发") def set_event(event): event.set() if __name__ == "__main__": event = threading.Event() t1 = threading.Thread(target=wait_for_event, args=(event,)) t2 = threading.Thread(target=set_event, args=(event,)) t1.start() t2.start() t1.join() t2.join()
三、线程池的使用
1、使用ThreadPoolExecutor创建线程池:
from concurrent.futures import ThreadPoolExecutor def worker(): print("线程执行中") if __name__ == "__main__": executor = ThreadPoolExecutor(max_workers=5) for _ in range(10): executor.submit(worker) executor.shutdown()
2、使用ThreadPoolExecutor的map函数实现批量任务执行:
from concurrent.futures import ThreadPoolExecutor def worker(num): return num * 2 if __name__ == "__main__": with ThreadPoolExecutor(max_workers=5) as executor: results = executor.map(worker, range(10)) for result in results: print(result)
四、GIL对多线程的影响
Python的全局解释器锁(Global Interpreter Lock,GIL)是一把全局互斥锁,限制了同一时刻只有一个线程执行Python字节码。在 CPU 密集型任务中,多线程并不能提升效率,但在 IO 密集型任务中,多线程可以有效提高程序的并发处理能力。
综上所述,Python多线程有两种写法:通过继承Thread类和通过实例化Thread类并传入可调用对象。线程间的同步与通信可以使用锁(Lock)进行同步和使用事件(Event)进行通信。线程池可以使用ThreadPoolExecutor来创建和管理线程。需要注意的是,Python的GIL会对多线程的性能造成一定的影响。