How to Kill a Thread With FG in Python
Multithreading allows different tasks to be executed simultaneously by processors in modern computers. In languages such as Python, this can be convenient for running long computational tasks or tasks that take a variable amount of time, such as Web requests. However, multithreading may prevent your Python program from being killed via a keyboard interrupt. You can use the Unix "fg" command to switch back to the foreground process after interrupting a thread running in the background.
Instructions
-
-
1
Start a Python program that uses threading. The following code is a bare-bones example Python program that uses threading:
import threading
class workerThread(threading.Thread):
def __init__ (self, value)
threading.Thread.__init__(self)
self.value = value
def run(self)
result = some_computation(self.value)
log("%s returns %s." % (self.value, result))def main():
workerThread(some_value).start()
workerThread(another_value).start()if __name__ == "__main__":
main() -
2
Press "Ctrl"+"Z" on your keyboard to suspend the current task.
-
-
3
Enter "kill %%" into the command line to send a soft kill signal to the running Python process.
-
4
Enter the "fg" command into the command prompt to switch back to Python running in the foreground.
-
5
Press "Ctrl"+"C" to kill the Python process and return to the command prompt.
-
1
Tips & Warnings
It is also possible to send the command "kill -9 %%" to terminate the Python process immediately.
References
- Photo Credit Thinkstock Images/Comstock/Getty Images