Python supports the creation of new threads for [bound or unbound] functions. They can help with multiprocessing. New threads are ideal for non-blocking operations like serving a GUI. If you want a server to begin certain operations in parallel with others, you may want to use new threads as opposed to new processes (which can provide the same parallel processing benefit). What are some advantages of using a thread to call a function?
The main reason you use threads is to leverage the capability of the server when you have complex operations (e.g., separate Python functions) that should run simultaneously. (Technically only one thread can execute at a time. But with small amounts of delay, non-blocking operations can happen in a way that will seem concurrent to the user.) Here are the advantages of using new threads (as opposed to forking a process):
- The server should perform better by not having the overhead of separate processes. A thread is not a separate process.
- It will produce no new processes; therefore you will not have to clean up zombie processes. Systems administrators have less work when there are fewer zombie processes.
- Different threads have access to the same memory addresses of the process (page 186 of Programming Python by Mark Lutz). Global variables in a Python program with multiple threads can make programming complex things simple. See "How Do You Troubleshoot a Python Error "UnboundLocalError: local variable 'x' referenced before assignment"?"
- New threads are architecture agnostic. This is different from Python's operating system forks (using os.fork would create a new process for a function call). If you are developing software with Python for Windows and Linux/Unix, using new threads is preferable to using system forks.
- A program can perform independently after the thread starts. This can allow for simultaneous execution of both the program and new thread. See "How Are Processes and Threads Different from Each Other in Python?" or "How Is a Process Different from a Daemon in Linux?"