簡體   English   中英

Python class 跨線程變量使用具有不同的值

[英]Python class variable usage across thread have different value

我對通過多線程訪問 class 變量感到困惑。 我在一個 django 應用程序中,我在服務器啟動時初始化一個 class 以注入一些配置。 然后根據用戶請求,我在該 class 上調用了一些方法,但配置為無。

class SharedService:
    _queue_name = None

    @staticmethod
    def config(queue_name=None):
        if queue_name:
            SharedService._queue_name = queue_name
        print(SharedService._queue_name)    # this print the "alert"

    @staticmethod
    def send_message(data):
        print(SharedService._queue_name)    # this print None should print "alert"

如果在啟動時加載的 django 設置 class 有用,我會這樣做:

SharedService.config(queue_name="alert")

在我剛剛調用的用戶端點中:

SharedService.send_message("blabla")

我確定它以前確實有效,但我們最近確實更新到 python 3.10 和 django 3.2 並且可能相關(或不相關!)

好的,這完全來自外場!

共享服務來自外部庫,實際上可以從兩個路徑導入,因為我們的 python 路徑中存在錯誤。

在設置文件中,我正在做

from lib.services import SharedService

並從請求處理代碼

from services import SharedService

這顯然創建了兩個不同的 class 定義,因此,第二個用法沒有初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM