簡體   English   中英

Python:線程中的全局變量

[英]Python: Global variables in threads

我試圖使我的程序脫機工作。 我決定這樣做的方法是讓主應用程序在其自己的線程中從內存中工作,而另一個線程從數據庫中讀取/寫入數據。

我在賦值之前被引用的變量有問題。

import threading

class Data():
        global a
        global b
        a = 1
        b = 1



class A(threading.Thread):
    def run(self):
        while True:
            a += 1


class B(threading.Thread):
    def run(self):
        while True:
            print a
            print b
            b -= 1


a_thr = A()
b_thr = B()
a_thr.start()
b_thr.start()

這與線程無關。 設置

global variable

不會在任何地方將此變量設置為全局變量,而只能在該函數中設置。 只要將我的更改添加到您的代碼中,它就可以運行。

class A(threading.Thread):

    def run(self):
        global a
        global b
        while True:
            a += 1



class B(threading.Thread):

    def run(self):
        global a
        global b
        while True:
            print a
            print b
            b -= 1

暫無
暫無

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

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