Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronize two processes using two different states

I am trying to work out a way to synchronize two processes which share data.

Basically I have two processes linked using shared memory. I need process A to set some data in the shared memory area, then process B to read that data and act on it.

The sequence of events I am looking to have is:

  1. B blocks waiting for data available signal
  2. A writes data
  3. A signals data available
  4. B reads data
  5. B blocks waiting for data not available signal
  6. A signals data not available
  7. All goes back to the beginning.

In other terms, B would block until it got a "1" signal, get the data, then block again until that signal went to "0".

I have managed to emulate it OK using purely shared memory, but either I block using a while loop which consumes 100% of CPU time, or I use a while loop with a nanosleep in it which sometimes misses some of the signals.

I have tried using semaphores, but I can only find a way to wait for a zero, not for a one, and trying to use two semaphores just didn't work. I don't think semaphores are the way to go.

There will be numerous processes all accessing the same shared memory area, and all processes need to be notified when that shared memory has been modified.

It's basically trying to emulate a hardware data and control bus, where events are edge rather than level triggered. It's the transitions between states I am interested in, rather than the states themselves.

So, any ideas or thoughts?

like image 417
Majenko Avatar asked Nov 03 '22 22:11

Majenko


1 Answers

Linux has its own eventfd(2) facility that you can incorporate into your normal poll/select loop. You can pass eventfd file descriptor from process to process through a UNIX socket the usual way, or just inherit it with fork(2).

Edit 0:

After re-reading the question I think one of your options is signals and process groups: start your "listening" processes under the same process group (setpgid(2)), then signal them all with negative pid argument to kill(2) or sigqueue(2). Again, Linux provides signalfd(2) for polling and avoiding slow signal trampolines.

like image 183
Nikolai Fetissov Avatar answered Nov 07 '22 23:11

Nikolai Fetissov