Malcolm Gooding
Malcolm Gooding

Reputation: 175

Python: can a child process pause/resume the parent

I'm trying to make a temperature monitoring module that saves the current temperature to a file continuously, and then uses matplotlib to draw a graph once whatever it was being used for finishes. I've got this functionality working, so I can use it like:

with TemperatureMonitoring():
    # do stuff

When __enter__ get called the process gets started, which is just an infinite loop that sleeps and writes to a file, and when __exit__ gets called the process is terminated and the file is plotted to the screen.

Now I want to make improvements, and so I'd like to make the child process control the parent; if the temperature gets too high for too long it will pause and wait for the computer to cool. This is my first time with the multiprocessing module, but it seems like if I pause the main process the child also gets paused. So if I do reach a critical state it won't be able to unpause itself. So the parent needs to be able to terminate the child when the code finished execution, and the child needs to be able to pause/resume the parent if necessary. Is there an obvious way to accomplish this?

Upvotes: 4

Views: 1151

Answers (2)

sgun
sgun

Reputation: 899

Using shared memory is the fastest IPC (inter process communication).

You can use posix_ipc package to establish shared memory and semaphores. Shared memory will keep the temperature and semaphores will let you make the process wait and continue.

When it comes to terminating a process I suggest performing that using a condition in the main loop. so that you can close all handles.

Upvotes: 0

Jonathan
Jonathan

Reputation: 2845

The cleanest way to do this is to use a duplex multiprocessing.Pipe. The parent can then send a command to the child to shutdown and the child can send a notification to the parent about the temperature level.

Upvotes: 1

Related Questions