Newbie question:
On Unix, in a program with a parent and some children:
- How can the parent alert the children efficiently to do some work.. ?
- Or how can the children wait for parent signal to start doing some work?
EDIT:
This program tries to do a complex computation in parallel, I have already used shared memory as a common workspaces for all children to update results and for data transfer.
What I need now is the parent say "start" efficiently to all its children...(called many times)
Thanks
Your ipc
tag says it all. You need to look into inter-process communuication:
- Shared memory.
- Semaphores.
- Pipes.
- Signals.
- Memory-mapped files.
- Sockets.
No doubt there are other possibilities but that's a good start.
How efficient each is depends pretty much on your use case. If you only need to notify a child to do something, signals is probably what I'd use. If you need to transfer some more information between processes, it's probably a good idea to fully specify the requirements.
One thing you may want to consider is to bypass all the inter-process stuff altogether and just use threads. At least in Linux, threads are first class citizens to the scheduler. Older UNIXes may have made a distinction (with user-mode threads) but that is not the case with Linux.
I've found that it's simpler to do it that way and your information is automatically shared (keeping in mind you still need to protect shared stuff with mutexes and such).
Another possibility if you're already committed to shared memory is to use signals. Assuming you've set aside sections of that memory for each child (and they know where they are), signals are probably the quickest way to notify a bunch of children for parallel work.
If your children just wait around in a select
loop with (for example) a 30-second timeout for doing periodic work, a signal will cause it to exit immediately with EINTR
. That gives you your efficient CPU usage while still giving immediate response.
Have a look at Beej's Guide to IPC to understand how it all works...it is an excellent guide. Beej also covers sockets as well on that same site.