python列表如何传递到线程?

21次阅读

python中传递列表给线程可通过args参数实现,线程内修改会直接影响原列表,因列表为可变对象多线程环境下需使用Threading.Lock确保线程安全;复杂逻辑可封装继承threading.Thread的类,统一管理数据与行为。

python列表如何传递到线程?

在Python中,将列表传递给线程非常简单,因为线程可以接收任意类型的参数,包括可变对象如列表。你只需要通过 threading.Thread构造函数,把列表作为参数传入目标函数即可。

1. 直接传递列表作为参数

使用 args 参数将列表传入线程执行的函数:

import threading <p>def worker(my_list): my_list.append("来自线程的数据") print(f"线程中的列表: {my_list}")</p><h1>主程序</h1><p>data = ["初始数据"] thread = threading.Thread(target=worker, args=(data,)) thread.start() thread.join()  # 等待线程完成</p><p>print(f"主线程中的列表: {data}")</p>

输出结果:

立即学习Python免费学习笔记(深入)”;

线程中的列表: ['初始数据', '来自线程的数据'] 主线程中的列表: ['初始数据', '来自线程的数据']

由于列表是可变对象,线程内对列表的修改会直接反映到主线程中。

2. 注意线程安全问题

多个线程同时修改同一个列表时,可能引发数据竞争。建议在操作共享列表时使用锁(threading.Lock)保护:

python列表如何传递到线程?

如知AI笔记

如知笔记——支持markdown的在线笔记,支持ai智能写作、AI搜索,支持DeepseekR1满血大模型

python列表如何传递到线程?27

查看详情 python列表如何传递到线程?

import threading <p>def safe_worker(my_list, lock): with lock: my_list.append(threading.current_thread().name) print(f"{threading.current_thread().name} 修改了列表")</p><p>data = [] lock = threading.Lock()</p><p>t1 = threading.Thread(target=safe_worker, args=(data, lock), name="线程-1") t2 = threading.Thread(target=safe_worker, args=(data, lock), name="线程-2")</p><p>t1.start() t2.start()</p><p>t1.join() t2.join()</p><p>print(f"最终列表: {data}")</p>

3. 使用类封装线程和数据

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

import threading <p>class ListWorker(threading.Thread): def <strong>init</strong>(self, data_list): super().<strong>init</strong>() self.data_list = data_list self.lock = threading.Lock()</p><pre class='brush:python;toolbar:false;'>def run(self):     with self.lock:         self.data_list.append(f"{self.name} 添加")

shared_list = [] threads = [ListWorker(sharedlist) for in range(3)]

for t in threads: t.start()

for t in threads: t.join()

print(f”类线程处理后的列表: {shared_list}”)

基本上就这些。只要把列表当作普通参数传入线程函数,注意多线程修改时加锁,就能安全使用。Python的列表本身不是线程安全的,关键在于你如何访问它。

text=ZqhQzanResources