How it works...

As you can see, we introduced a minimal number of changes to the code of our application. All the mechanisms and the API for reading and writing data remain the same. The crucial difference hides behind a single line of code:

  int ret = mkfifo(kSharedFile.c_str(), 0600);

This line creates a special type of file called named pipe. It looks like a regular fileā€”it has a name, permission attributes, and a modification time. However, it does not store any real data. Everything written to this file is immediately delivered to the processes that read from this file.

This difference has a number of consequences. Since no real data is stored in the file, all reading attempts are blocked until any data is  written. Similarly, writes are blocked until previous data is read by the readers.

As a result, there is no further need for external data synchronization. Take a look at the Reader class implementation. It does not have a retry loop in the constructor or in the Read method.

To test that we really do not need to use any additional synchronization, we added an artificial delay after writing each of the messages:

    std::this_thread::sleep_for(std::chrono::milliseconds(10));

When we build and run the application, we can see the following output:

Each Write method is followed by the proper Read method, despite the fact that we did not add any delays or checks anywhere in the Reader code. The IPC mechanisms of the operating system take care of data synchronization transparently for us, leading to cleaner and more readable code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.80.122