我正在為 Python 中的執行緒通信而苦苦掙扎。我顯然錯過了一些東西,但我是 Python 的新手,所以我不太清楚自己在做什么。
當服務器收到 GET 請求時,我希望它從一個單獨的執行緒中獲取兩個數字(x 和 y 坐標),該執行緒不斷更新這些值并將這些數字作為回應回傳。
我有一個簡單的 Django 專案,其結構如下:

它非常基礎,根據教程制作。
當服務器啟動時,我啟動一個執行緒,它看起來在一個單獨的執行緒中啟動我的坐標生成器:
class GpsMockCoordsServiceConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'gps_mock_coords_service'
def ready(self):
if os.environ.get('RUN_MAIN', None) != 'true':
_thread.start_new_thread(CoordsTracker.launch_recognition, ())
CoordsTracker 類看起來像這樣:
coords = None
class CoordsTracker:
#coords = None #tried placin it here, but same effect - it is None when retreived from views.py
logger = logging.getLogger("CoordsTrackerLogger")
@staticmethod
def draw_contours(mask, frame, color):
......
for stuff in stuffs:
......
CoordsTracker.set_coords((x, y))
......
@staticmethod
def launch_recognition():
........
while True:
........
CoordsTracker.draw_contours(....)
........
@staticmethod
def set_coords(new_coords):
global coords
CoordsTracker.logger.debug("setting coords " str(new_coords))
coords = new_coords # here coords var is OK
@staticmethod
def get_coords():
CoordsTracker.logger.debug(coords) # Here it is OK if I call this method from draw_contours() and is not OK if I call this from views.py file.
return coords
views.py 類只有這個方法:
def index(request):
# with CoordsTracker.coords_thread_lock:
coords = CoordsTracker.get_coords()
logger.debug("Got coords: " str(coords)) #if I do a GET request this prints 'Got coords: None'
return HttpResponse(str(coords))
UPD:和朋友除錯了一段時間后,發現set_coords()方法在一個行程中呼叫,而get_coords()方法在另一個行程中呼叫。
uj5u.com熱心網友回復:
我建議使用您擁有的中間件實作某種 IPC。但如果它是一次性專案,您可以從 wsgi.py 某處啟動執行緒 (launch_recognition)。這將確保它都在同一行程中運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/334406.html
