0

I want to terminate my program when press Ctrl-C, code as follow:

#!/usr/bin/env python
# encoding: utf-8

import multiprocessing
import time
import signal
import sys

def init_worker():
    signal.signal(signal.SIGINT, signal.SIG_IGN)

def worker():
    while(True):
        time.sleep(1.1234)
        print "Working..."

if __name__ == "__main__":
    pool = multiprocessing.Pool(50, init_worker)
    try:
        for i in range(50):
            pool.apply_async(worker)

        # time.sleep(10)
        pool.close()
        pool.join()

    except KeyboardInterrupt:
        print "Caught KeyboardInterrupt, terminating workers"
        pool.terminate()
        pool.join()

but this can not work right

roger
  • 9,063
  • 20
  • 72
  • 119

1 Answers1

0

You can try this way:

import multiprocessing
import time
import signal


def init_worker():
    signal.signal(signal.SIGINT, signal.SIG_IGN)


def worker():
    while(True):
        time.sleep(1.1234)
        print "Working..."


if __name__ == "__main__":
    pool = multiprocessing.Pool(10, init_worker)
    result = []
    for i in range(10):
        result.append(pool.apply_async(worker))
    try:
        while True:
            time.sleep(0.5)
            if all([r.ready() for r in result]):
                break

    except KeyboardInterrupt:
        pool.terminate()
        pool.join()

    else:
        pool.close()
        pool.join()
Avernial
  • 151
  • 9