Sunday, 20 December 2015

Python: multiprocessing: terminate: Terminate a process


‘terminate()’ is used to terminate the process.

from multiprocessing import Process
import multiprocessing
import time

def print_data():
    name = multiprocessing.current_process().name
    id = multiprocessing.current_process().pid
    print(name, id)
    time.sleep(5)
    print("Processing finished")

if __name__=="__main__":
    proc1 = Process(name='process1', target=print_data)
    proc1.start()

    print("Is proc1 alive ",proc1.is_alive())
    time.sleep(1)
    proc1.terminate()
    proc1.join()
    print("Is proc1 alive ",proc1.is_alive())


    print("Finished")


Output
Is proc1 alive  True
process1 31842
Is proc1 alive  False
Finished


Make sure, you called join() after calling terminate method to give time to update the status flags of this process.

Note:
a.   The descendant processes of the process will not be terminated – they will simply become orphaned.
b.   start(), join(), is_alive(), terminate() and exitcode methods should only be called by the process that created the process object.





Previous                                                 Next                                                 Home

No comments:

Post a Comment