読者です 読者をやめる 読者になる 読者になる

WELCOME TO EASTWORLD

Eastworld でドロイド遊び Rapiro が主人公 ラズパイが好物

番外編 お手玉遊び その4

 

お手玉遊びに、新しいドリルを追加。

child.kill() という物騒な名前の金粉を振りかければ、うたた寝中の召使たちもサッと起き上がる。

 

import multiprocessing as mp
from time import sleep
from random import randint
from os import getpid
import psutil

parent_pid = getpid()
#print("parent process id: %d" % parent_pid)
parent = psutil.Process(parent_pid)


def worker(num,nap):
    print('Worker%d started napping...' % num)
    print('\n')
    sleep(nap)
    print('Worker%d wakes up after %d sec' % (num,nap))
    return

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        time_to_nap = randint(1,30)
        p = mp.Process(target=worker, args=(i,time_to_nap))
        #print(p)
        jobs.append(p)
        print('Worker%d, you can nap for %d sec' % (i,time_to_nap))
        p.start()
        #print(p)
        sleep(0.1)
    while True:
        i = raw_input('Press any key to interrupt...\n')
        if not i:
            try:
                for child in parent.children():
                    child.kill()
                print('Everybody woke up')
                break
            except Exception as e:
                print(e)
    print('\nAll right, everybody back to work!\n')
    sleep(0.1)
    for i in range(5):
        print(jobs[i]

 

<メモ>

実行結果の例:

$ sudo python test.py
Worker0, you can nap for 8 sec
Worker0 started napping...


Worker1, you can nap for 22 sec
Worker1 started napping...


Worker2, you can nap for 3 sec
Worker2 started napping...


Worker3, you can nap for 22 sec
Worker3 started napping...


Worker4, you can nap for 6 sec
Worker4 started napping...


Press any key to interrupt...
Worker2 wakes up after 3 sec
Worker4 wakes up after 6 sec
Worker0 wakes up after 8 sec

*** ここでキー入力した ***

Everybody woke up

All right, everybody back to work!

<Process(Process-1, stopped)>
<Process(Process-2, stopped[SIGKILL])>
<Process(Process-3, stopped)>
<Process(Process-4, stopped[SIGKILL])>
<Process(Process-5, stopped)>

Worker1と3(Process-2と4)を、うたた寝中に叩き起こした。

(実際には、まだ sleep 中の子プロセスを kill()  。 )

 

なお、オンライン・エディターではエラーになる。