Python multiprocessing: two threads stopping each other

I need to move a small motor carriage on the rail. There is an infrared detector on the rail to prevent entry too far. The whole system is controlled by Raspberry Pi 3.

I am trying to configure two processes using a multiprocessing package: the first is this move_process, which basically just calls a function that moves the engine for the selected number of steps.

def move():
    motor.step(steps, direction, stepmode)
    watch_process.terminate()

The second is one watch_processthat calls an infinite loop function, awaiting input from the IR detector:

def watch()
    while True:
        detector_input = GPIO.input(18)
        if detector_input == False:
            move_process.terminate()
            break

I want to watch_processkill move_processif the detector sends input. I also want to move_processkill watch_processif everything went fine, i.e. When the engine successfully moved without starting the detector.

, , "":

def on_go_pressed():
    move_process = multiprocessing.Process(target=move)
    watch_process = multiprocessing.Process(target=watch)
    move_process.start(), watch_process.start()

, ? . .

EDIT: typo

+4
1

, . Process.terminate() SIGTERM .

PID. .

, .

import os
import signal
import multiprocessing

def watch(pipe)
    move_process_pid = pipe.recv()
    while True: 
       if not GPIO.input(18):
           os.kill(move_process_pid, signal.SIGTERM)
           return

def move(pipe):
    watch_process_pid = pipe.recv()
    motor.step(steps, direction, stepmode)
    os.kill(watch_process_pid, signal.SIGTERM)  

def on_go_pressed():
    move_process_reader, move_process_writer = multiprocessing.Pipe(False)
    watch_process_reader, watch_process_writer = multiprocessing.Pipe(False)
    move_process = multiprocessing.Process(target=move, args=(move_process_reader,))
    watch_process = multiprocessing.Process(target=watch, args=(watch_process_reader,))

    move_process.start()
    watch_process.start()

    move_process_writer.send(watch_process.pid)
    watch_process_writer.send(move_process.pid)
0

Source: https://habr.com/ru/post/1672296/


All Articles