简体   繁体   中英

How can I make one multiprocessed loop stop another when a variable is set in python?

We are creating a manufacturing test for some hardware right now in Python. We have a UI that a user will use to run the testing scripts written in Python over a TCP Socket.

Right now I am trying to write a test that simultaneously runs a loop that sends a command to the hardware and runs a loop that listens for an interaction from the UI over the TCP connection (ie The user clicks 'Yes' button). Once a message is received from the TCP connection, some variable will be set that will then break from the other loop sending commands to the hardware.

Right now, we are thinking of using MultiProcessing instead of MultiThreading because there will not be too much overhead since there are only two simple loops. So each loop will be ran in a different process.

My question is: can I use a global variable in the test script that will be set by the TCP loop Process that the hardware loop Process can check against and be stopped when the global variable is set?

EDIT: We are using c# to write the UI and it is a management decision to use Python for the testing scripts rather than bunching them into c# with the UI. Whether or not using Python over a TCP connection with c# is a the best approach is outside of my paygrade.

A global variable won't be shared across processes but will be duplicated. This means they will both have their own copy of it. If the first one changes its value, the second won't.

Python's simplest way to allow concurrent/parallel loops to communicate with each other is using a messaging Queue.

The multiprocessing Queue is what you want to use:

from queue import Empty
from multiprocessing import Process, Queue

def process1(queue):
    while 1:
        try:
            message = queue.get(block=False)
            if message == "you must stop my dear":
                return
        except Empty:
            do_your_job()


def process2(queue):
    do_something()
    queue.put("you must stop my dear")


q = Queue()
p1 = Process(target=process1, args=(q, ))
p2 = Process(target=process2, args=(q, ))
p1.start()
p2.start()

This is a very simple example, I hope it gives the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM