Khanh Le Tran
Khanh Le Tran

Reputation: 900

How can i update global variable outside a thread?

I have a global varibale that share for all of function in my flask socketio server and a thread to start another feature to send notification for which connected to flask socketio server. The thread start from running and the global variable is passed into. The problem is when i change the global varibale outside the thread, it's not updated in the thread.

    from flask import Flask, request
    from flask_socketio import SocketIO, emit
    from flask_cors import CORS, cross_origin
    
    from generate_audio import *
    from manage_time import receive_data, clock
    from manage_audio import set_audio
    import threading
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    socketio = SocketIO(app, cors_allowed_origins="*")
    CORS(app)
    
    a = 0
    
    @app.route("/demo", methods=["POST"])
    @cross_origin(origin='localhost',headers=['Content-Type','Authorization'])
    def receive_request():
        global a
        a += 1
        return "Done"

   def clock(a):
      while True:
         print(a)
    
    if __name__ == "__main__":
        global a
        threading.Thread(target=clock, args=(a,)).start()
        socketio.run(app, port=5000, debug=True, host="0.0.0.0")

How can i update a value inside the thread? It's always equal 0, i want it will be increased everytime i send a request to "/demo".

Upvotes: 0

Views: 297

Answers (1)

danilo3dr
danilo3dr

Reputation: 41

you can modify global variables like this:

global a
a += 1

Upvotes: 1

Related Questions