跳转到主内容
新派编程网 - 新潮编程理念,全新技术课堂!

python列表如何传递到线程?

在Python中传递列表给线程可通过args参数实现,线程内修改会直接影响原列表,因列表为可变对象;多线程环境下需使用threading.Lock确保线程安全;复杂逻辑可封装成继承threading.Thread的类,统一管理数据与行为。 在Python中,将列表传递给线程非常简单,因为线程可以接收任意类型的参数,包括可变对象如列表。你只需要通过 threading.Thread 的构造函数,把列表作为参数传入目标函数即可。 1. 直接传递列表作为参数 使用 args 参数将列表传入线程执行的函数:
import threading

def worker(my_list): my_list.append("来自线程的数据") print(f"线程中的列表: {my_list}")

主程序

data = ["初始数据"] thread = threading.Thread(target=worker, args=(data,)) thread.start() thread.join() # 等待线程完成

print(f"主线程中的列表: {data}")

输出结果: 立即学习 “ Python免费学习笔记(深入) ”;
线程中的列表: ['初始数据', '来自线程的数据'] 主线程中的列表: ['初始数据', '来自线程的数据']
由于列表是可变对象,线程内对列表的修改会直接反映到主线程中。 Python 3.14.3 微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。 下载 2. 注意线程安全问题 多个线程同时修改同一个列表时,可能引发数据竞争。建议在操作共享列表时使用锁( threading.Lock )保护:
import threading

def safe_worker(my_list, lock): with lock: my_list.append(threading.current_thread().name) print(f"{threading.current_thread().name} 修改了列表")

data = [] lock = threading.Lock()

t1 = threading.Thread(target=safe_worker, args=(data, lock), name="线程-1") t2 = threading.Thread(target=safe_worker, args=(data, lock), name="线程-2")

t1.start() t2.start()

t1.join() t2.join()

print(f"最终列表: {data}")

3. 使用类封装线程和数据 如果你的逻辑较复杂,可以用继承 threading.Thread 的方式封装列表和线程行为:
import threading

class ListWorker(threading.Thread): def init(self, data_list): super().init() self.data_list = data_list self.lock = threading.Lock()

def run(self):
    with self.lock:
        self.data_list.append(f"{self.name} 添加")
shared_list = [] threads = [ListWorker(sharedlist) forin range(3)]for t in threads: t.start()for t in threads: t.join()print(f"类线程处理后的列表: {shared_list}") 基本上就这些。只要把列表当作普通参数传入线程函数,注意多线程修改时加锁,就能安全使用。Python的列表本身不是线程安全的,关键在于你如何访问它。

相关文章