0

我想在按下时终止我的程序Ctrl-C,代码如下:

#!/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()

但这不能正常工作

4

1 回答 1

0

你可以这样试试:

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()
于 2016-01-29T01:50:31.620 回答