How to terminate process in Python?


Reading official documentation

Multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine.'

Python2

Python3

More information and examples about GIL (Global Interpreter Lock): http://www.dabeaz.com/GIL/ https://www.youtube.com/watch?v=Obt-vMVdM8s

Example

    from time import time
    from multiprocessing import Process

    def infinite_loop(time_sleeping, start_point=0):
        i = start_point
        start_time = time()
        while True:
            current_time = time()
            if (current_time - start_time) >= time_sleeping:
                i += 1
                start_time = current_time
                print("i =", i)

    p = Process(target=infinite_loop, name="clean_imap",
                    args=(2,))
    p.start()
    p.join(60)
    if p.is_alive():
        print("Function is exceeding limit of execution "
                    "let's kill it...")
        p.terminate()
        p.join()