首页 > 解决方案 > 如何在python中的多个线程之间正确共享信息?

问题描述

我正在构建一个系统,该系统需要从一个线程(第一个生成信息)与第二个线程(套接字)共享信息。

如何访问socketThread中Detector Thread的信息?我尝试将变量设置为全局,它们可以在 main.py 文件中找到。虽然我无法在套接字线程中访问它们。

from objDetect import *
from socketclient import *

import threading

   

detectorThread = threading.Thread(name='detect', target=detectorWorker)
socketThread = threading.Thread(name='api', target=runSocket)
socketThread.setDaemon(True)

try:
    detectorThread.start()
    socketThread.start()
except:
    print('[ERROR] Couldnt start detector.')

标签: pythonmultithreadingsockets

解决方案


您可以使用模块中的各种线程安全队列之一queue

https://docs.python.org/3/library/queue.html


推荐阅读