Skip to content

Instantly share code, notes, and snippets.

@James-E-A
Last active July 26, 2025 06:50
Show Gist options
  • Save James-E-A/478576313ae6d76bf0ef04001b557398 to your computer and use it in GitHub Desktop.
Save James-E-A/478576313ae6d76bf0ef04001b557398 to your computer and use it in GitHub Desktop.
Python run a block of code in a background thread immediately
import threading
def thread_start_immed(*args, _threading_daemon=True, **kwargs):
"""Usage:
@thread_start_immed("my background thread", _threading_daemon=False)
def t(name):
import time
time.sleep(3)
print(f"Hello from {name}!")
print("Started background thread:", t)
"""
# explicitly denoting objects to be transferred to the thread by passing them as arguments
# can make developer intent far more explicit than relying on implicit closure bindings
return lambda f: _start_thread(target=f, args=args, kwargs=kwargs, daemon=_threading_daemon)
def _start_thread(*args, **kwargs):
t = threading.Thread(*a, **kwargs)
t.start()
return t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment