Python3 多线程学习笔记
什么是多线程?
多线程是指在一个进程内同时执行不同的代码段,每个代码段称为一个线程。多线程可以提高程序效率,能够使程序在单个CPU上运行更快。
Python 中的多线程
Python 拥有强大的多线程库,其中最常用的是 threading 模块。使用 threading 模块可以轻松地创建和管理线程。
创建线程
创建线程有两种方式:函数和类。下面分别介绍。
使用函数创建线程
可以通过定义一个函数来创建一个线程,这个函数将作为线程的执行体,如下所示:
pythonCopy Codeimport threading
def thread_func():
# 线程的执行体
pass
thread = threading.Thread(target=thread_func)
thread.start()
使用类创建线程
也可以通过定义一个类来创建一个线程,如下所示:
pythonCopy Codeimport threading
class MyThread(threading.Thread):
def run(self):
# 线程的执行体
pass
thread = MyThread()
thread.start()
线程同步
多线程并发执行时,可能会出现数据竞争(即多个线程同时对同一数据进行操作)的情况,需要通过同步机制来避免。Python 提供了多种同步机制,包括 Lock、RLock、Condition、Semaphore 等。
下面以 Lock 为例来介绍线程同步的使用方法:
pythonCopy Codeimport threading
lock = threading.Lock()
def func():
with lock:
# 对共享资源的操作
pass
线程池
线程池可以避免频繁创建和销毁线程的开销,提高程序效率,Python 提供了 ThreadPoolExecutor 和 ProcessPoolExecutor 两个线程池,其中 ThreadPoolExecutor 用于线程池,ProcessPoolExecutor 用于进程池。
下面以 ThreadPoolExecutor 为例来介绍线程池的使用方法:
pythonCopy Codefrom concurrent.futures import ThreadPoolExecutor
def func(arg):
# 线程的执行体
pass
with ThreadPoolExecutor(max_workers=4) as executor:
for i in range(10):
executor.submit(func, i)
实例
下面给出一个简单的多线程实例:
pythonCopy Codeimport threading
class Printer(threading.Thread):
def __init__(self, val):
threading.Thread.__init__(self)
self.val = val
def run(self):
for i in range(self.val):
print('hello')
t1 = Printer(5)
t2 = Printer(10)
t1.start()
t2.start()
t1.join()
t2.join()
print('done')
输出结果如下:
Copy Codehello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
done
上述实例中,创建了两个打印 'hello' 的线程,并将它们启动。由于是多线程并发执行,因此输出的 'hello' 会交错出现。最后输出 'done' 表示线程执行完毕。
以上就是 Python3 多线程学习笔记的内容,希望对大家有所帮助。