Ubuntu配置Python多线程环境指南
Ubuntu系统通常预装Python 3,但需确认版本是否符合需求(推荐Python 3.8及以上)。通过以下命令检查Python 3版本:
python3 --version
若未安装,使用以下命令安装Python 3及pip(Python包管理工具):
sudo apt update
sudo apt install python3 python3-pip
Python内置threading模块用于实现多线程,以下是基础示例:
import threading
def print_numbers():
"""打印数字的线程任务"""
for i in range(1, 6):
print(f"Number: {i}")
def print_letters():
"""打印字母的线程任务"""
for letter in 'ABCDE':
print(f"Letter: {letter}")
# 创建线程对象(指定目标函数)
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# 启动线程(执行目标函数)
thread1.start()
thread2.start()
# 等待线程完成(主线程阻塞,直到子线程结束)
thread1.join()
thread2.join()
print("All threads have finished.")
import threading
def worker(num):
"""带参数的线程任务"""
print(f"Worker {num} is running")
# 创建带参数的线程
threads = []
for i in range(3):
thread = threading.Thread(target=worker, args=(i,))
threads.append(thread)
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
对于批量任务,concurrent.futures.ThreadPoolExecutor可简化线程管理:
from concurrent.futures import ThreadPoolExecutor
def print_numbers():
"""打印数字的线程任务"""
for i in range(1, 6):
print(f"Number: {i}")
def print_letters():
"""打印字母的线程任务"""
for letter in 'ABCDE':
print(f"Letter: {letter}")
# 创建线程池(最大并发数为2)
with ThreadPoolExecutor(max_workers=2) as executor:
# 提交任务(返回Future对象)
executor.submit(print_numbers)
executor.submit(print_letters)
print("All threads have finished.")
将上述代码保存为multithreading_example.py,在终端中导航至脚本所在目录,运行:
python3 multithreading_example.py
多线程访问共享资源(如全局变量)时,需使用threading.Lock避免数据竞争:
import threading
# 共享资源
counter = 0
# 创建锁对象
lock = threading.Lock()
def increment_counter():
"""递增计数器的线程任务"""
global counter
for _ in range(100000):
with lock: # 获取锁(自动释放)
counter += 1
# 创建多个线程
threads = []
for i in range(5):
thread = threading.Thread(target=increment_counter)
threads.append(thread)
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
print(f"Final counter value: {counter}") # 应为500000
Python的GIL限制同一时间仅一个线程执行Python字节码,因此:
multiprocessing模块(多进程绕过GIL);虚拟环境可隔离项目依赖,避免全局Python环境混乱。使用venv创建虚拟环境:
# 创建虚拟环境(名为myenv)
python3 -m venv myenv
# 激活虚拟环境
source myenv/bin/activate
# 安装依赖(如requests库)
pip install requests
# 退出虚拟环境
deactivate
chmod +x multithreading_example.py),但通常直接用python3运行即可;logging模块替代print语句,便于调试多线程程序(如记录线程名称、时间戳)。