Page 1 of 1

Small "threaded" function decorator

Posted: Mon Jun 29, 2020 6:23 am
by Zeus

Code: Select all

from listeners.tick import GameThread

def threaded(fn):
    def wrapper(*args, **kwargs):
        thread = GameThread(target=fn, args=args, kwargs=kwargs)
        thread.daemon = True
        thread.start()
    return wrapper

def load():
    do_something_that_blocks()

@threaded
def do_something_that_blocks():
    requests.get("https://sourcepython.com")



Something I've run into a bunch of times is needing something run without blocking the main game thread like external HTTP calls to the Discord API. Since network calls, especially slow ones will cause the game to wait until it's complete; this allows me to keep the game going while doing what I need to on the backend.

Of course you will not be able to get a value returned directly from the call; instead you'll have to manage that outside of the function. This works fine for my use case since it's fire and forget.

Maybe worth adding something like this to SP? Unless theres a simplier pattern that can allow one to not block the game thread.