Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I'm trying to write a game server to try out flask. The game exposes an API via REST to users.

It's easy for users to perform actions and query data, however I'd like to service the "game world" outside the app.run() loop to update game entities, etc.

 Given that Flask is so cleanly implemented, I'd like to see if there's a Flask way to do this. Need some help!

1 Answer

0 votes
by (25.1k points)

To create a background thread in flask you would have to use theading module in python. Also you would have to take care of stting locks on a common data that will be manipulated by multiple threads. This is because if there is no lock on data then we would be facing a race condition that will either corrupt the data or make it behave unexpectedly.

If you wish you can learn more about python using this tutorial video:

Here is code to help you do that:

import threading

import atexit

from flask import Flask

INTERVAL = 5 # Time Interval

# data accessed by all threads

data = {}

# lock to control access to variable

lock = threading.Lock()

# thread handler

thread = threading.Thread()

def create_application():

    app = Flask(__name__)

    def interrupt():

        global thread

        thread.cancel()

    def perfromTask():

        global commonDataStruct

        global thread

        with lock:

        # Do your stuff with commonDataStruct Here

        # Set the next thread to happen

        thread = threading.Timer(POOL_TIME, doStuff, ())

        thread.start()   

    def start():

        # Do initialisation stuff here

        global thread

        # Create your thread

        thread = threading.Timer(POOL_TIME, doStuff, ())

        thread.start()

    # Initiate

    start()

    # When you kill Flask (SIGTERM), clear the trigger for the next thread

    atexit.register(interrupt)

    return app

app = create_application()          

Related questions

0 votes
1 answer
asked Jul 17, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 31, 2019 in Java by noah kapoor (5.3k points)
0 votes
1 answer
asked Nov 5, 2020 in Data Science by blackindya (18.4k points)

Browse Categories

...