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

在Python中,将列表传递给线程非常简单,因为线程可以接收任意类型的参数,包括可变对象如列表。你只需要通过 threading.Thread 的构造函数,把列表作为参数传入目标函数即可。
使用 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免费学习笔记(深入)”;
线程中的列表: ['初始数据', '来自线程的数据'] 主线程中的列表: ['初始数据', '来自线程的数据']
由于列表是可变对象,线程内对列表的修改会直接反映到主线程中。
多个线程同时修改同一个列表时,可能引发数据竞争。建议在操作共享列表时使用锁(threading.Lock)保护:
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>如果你的逻辑较复杂,可以用继承 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的列表本身不是线程安全的,关键在于你如何访问它。
以上就是python列表如何传递到线程?的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号