Keyboard shortcuts

Press โ† or โ†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Decorator that runs a function in a thread

I wrote a small decorator that will convert any function to run in a thread:

import threading

def run_threaded(fn):
    """A decorator that makes a function run in a thread."""

    def run(*k, **kw):
        t = threading.Thread(target=fn, args=k, kwargs=kw)
        t.start()
        return t

    return run

Example:

@run_threaded
def add(x, y):
    # This runs in a separate thread.
    print(x+y)
	
add(1+2)

Thatโ€™s it!


Last updated on September 28, 2024. For any questions/feedback, email me at hi@stavros.io.