Click here to Skip to main content
15,878,748 members
Articles / Programming Languages / C++
Article

Synchronization of multiple reader and writer processes using Win32 APIs

Rate me:
Please Sign up or sign in to vote.
3.65/5 (21 votes)
10 Feb 2006CPOL2 min read 102.8K   3K   45   32
An article on the use of shared memory and events.

Image 1

Introduction

This source code demonstrates how to use Win32 events to solve the multiple readers and writers problem. On compilation of this source code, you will get a console application that can act as both a reader and a writer of the shared memory. Multiple instances of the same executable should be executed for testing. Only one write operation is allowed at a time. If there is already a write operation going on, all other write and read operations will get blocked. However, multiple read operations are allowed. If read operations are underway, a write operation will wait for all read operations to get over before proceeding. This synchronization mechanism ensures proper synchronization of readers and writers, and helps in prevention of data corruption at all times.

Image 2

Background

I was asked to design a solution for the multiple readers and writers problem, in a recent interview. I described at an abstract level what I had in mind. But the more that I thought on this, the more I was convinced that I should implement it to flesh out the ideas that I had in mind. Hence, this source code.

Image 3

Using the code

This source code has a shared memory which the readers and writers are trying to use. The synchronization is done using events. I have tried to add comments at the right places to make understanding of this source code easier.

Although, this code is in C++, it can easily be converted to C. This program doesn't use any object oriented concept or design.

The code includes <tchar.h> and uses generic functions at many places. However, this code was compiled and tested with ASCII builds only. The code may not compile or work for Unicode builds.

Following is the initialization function which initializes the events and the shared memory:

bool Initialize()
{
     //Trying to be defensive
     for (int ii = 0; ii < MAX_READ_PROCESSES_ALLOWED; ii++)
     {
          g_hReadEvent[ii] = NULL;
     }
     
     TCHAR szBuffer[32];  //big enough to hold the name
     
     //Creating Read events
     for (ii = 0; ii < MAX_READ_PROCESSES_ALLOWED; ii++)
     {
          _stprintf(szBuffer, _T("%s %d"), 
                             g_szReadEventName, ii);
          
          //Creates or opens event depending, 
          //on whether already exists or not
          g_hReadEvent[ii] = CreateEvent( 
               NULL,        //default security
               false,       //auto reset
               true,        //default state signaled
               szBuffer);
          
          if (NULL == g_hReadEvent[ii])
          {
               return false;
          }
     }
     
     //Write Event
     //Creates or opens event, depending 
     //on whether already exists or not
     g_hWriteEvent = CreateEvent( 
          NULL,             //default security
          false,            //auto reset
          true,             //default state signaled
          g_szWriteEventName);
     
     if (NULL == g_hWriteEvent)
     {
          return false;
     }
     
     //Shared Memory Stuff
     //Creates or opens shared memory, 
     //depending on whether already exists or not
     g_hSharedMemory = CreateFileMapping(
          INVALID_HANDLE_VALUE,    // use paging file
          NULL,                    // default security 
          PAGE_READWRITE,          // read/write access
          0,                       // max. object size 
          MAX_SH_MEM_SIZE,         // buffer size  
          g_szShareMemoryName);    // name of mapping object
     
     if (NULL == g_hSharedMemory || 
         INVALID_HANDLE_VALUE == g_hSharedMemory) 
     { 
          cout << "Error occured while" 
                  " creating file mapping object :" 
               << GetLastError() << "\n";
          return false;
     }
     
     g_pBuffer = 
          (LPTSTR) MapViewOfFile(g_hSharedMemory, // handle to map object
          FILE_MAP_ALL_ACCESS, // read/write permission
          0,                   
          0,                   
          MAX_SH_MEM_SIZE);           
     
     if (NULL == g_pBuffer) 
     { 
          cout << "Error occured while mapping" 
                  " view of the file :" << GetLastError() 
               << "\n";
          return false;
     }
     
     return true;
}

Following is the read function which blocks itself on write and read events:

void ReadAndPrint()
{
     cout << "Trying to read and print the shared memory...\n";
     
     //Wait to make sure all writing 
     //operations are done and data is in sync
     bool bContinue = true;
     
     while(bContinue)  //We want to block until we get to read
     {
          cout << "Waiting for write operation to complete...\n";
          
          DWORD dwWaitResult = WaitForSingleObject(g_hWriteEvent, INFINITE );
          
          if (WAIT_OBJECT_0 == dwWaitResult)
          {
               bool bEventFound = false;
               
               for (int ii = 0; ii < MAX_READ_PROCESSES_ALLOWED; ii++)
               {
                    DWORD dwWaitResult = 
                      WaitForSingleObject(g_hReadEvent[ii], WAIT_TIME_OUT);
                    
                    if (WAIT_OBJECT_0 == dwWaitResult)
                    //The state of the specified object is signaled
                    {
                         bEventFound = true;
                         
                         cout << "Setting the Write Event...\n";
                         SetEvent(g_hWriteEvent);
                         
                         //Reading the shared memory
                         cout << "Shared Memory: " 
                              << g_pBuffer << "\n";
                         
                         cout << "Setting the Read Event...\n";
                         SetEvent(g_hReadEvent[ii]);
                         
                         bContinue = false;
                         break; //get out of the for loop
                    }
                    else
                    {
                         continue;
                         //The time-out interval elapsed, 
                         //and the object's state is nonsignaled.
                    }
               } // for
               
               if (false == bEventFound)
               {
                    cout << "Setting the Write Event...\n";
                    SetEvent(g_hWriteEvent);
                    
                    //SwitchToThread();
                    Sleep(WAIT_TIME_OUT);
               }
          }
          else
          {
               cout << "Error occured while waiting :" 
                    << GetLastError() << "\n";
          }
          
     } //while
}

Similarly, the write function uses events to synchronize:

void WriteAndPrint()
{
     cout << "Trying to write and print the shared memory...\n";
     
     cout << "Waiting for write operation to complete...\n";
     
     //Wait to make sure all writing operations are done and data is in sync
     if (WAIT_OBJECT_0 == WaitForSingleObject(g_hWriteEvent, INFINITE ))
     {
          cout << "Waiting for all read operations to complete...\n";
          
          DWORD dwWaitResult = WaitForMultipleObjects( 
               MAX_READ_PROCESSES_ALLOWED,   // number of handles in array
               g_hReadEvent,  // array of read-event handles
               TRUE,         // wait until all are signaled
               INFINITE);    // indefinite wait
          
          if (WAIT_OBJECT_0 == dwWaitResult)
          {
               cout << "Enter a string (without spaces): ";
               
               cin >> g_pBuffer;
               
               //Reading the shared memory
               cout << "Shared Memory: " << g_pBuffer << "\n";
          }
          else
          {
               cout << "Error occured while waiting :" 
                    << GetLastError() << "\n";
          }
          
          cout << "Setting the Write Event...\n";
          SetEvent(g_hWriteEvent);
          
          cout << "Setting the Read Events...\n";
          for (int ii = 0; ii < MAX_READ_PROCESSES_ALLOWED; ii++)
          {
               SetEvent(g_hReadEvent[ii]);
          }
     }
     else
     {
          cout << "Error occured while waiting :" 
               << GetLastError() << "\n";
     }
}

The de-initialization function is shown next. This function takes care of the de-initialization of the shared memory and events.

void DeInitialize()
{
     for (int ii = 0; ii < MAX_READ_PROCESSES_ALLOWED; ii++)
     {
          CloseHandle(g_hReadEvent[ii]);
     }
     
     CloseHandle(g_hWriteEvent);
     
     UnmapViewOfFile(g_pBuffer);
     
     CloseHandle(g_hSharedMemory);
}

Points of Interest

If you are a newbie to events, make sure you understand the difference between manual and auto-reset events. I have used auto-reset events, they are very handy to use.

History

  • Feb 2nd 2006 - Removed a wrong statement - CloseHandle(g_hReadEvent); from Initialize().

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionA better way? Pin
Lee Gaiteri13-May-21 7:24
Lee Gaiteri13-May-21 7:24 
QuestionQuestion Pin
Ajay_Tiwari10-Apr-15 9:50
Ajay_Tiwari10-Apr-15 9:50 
GeneralMy vote of 4 Pin
Pranit Kothari27-Oct-12 8:20
Pranit Kothari27-Oct-12 8:20 
GeneralMicro-corrigendum !!! [modified] Pin
ramayan10220-May-08 14:17
ramayan10220-May-08 14:17 
GeneralRe: Micro-corrigendum !!! Pin
Swarajya Pendharkar23-May-08 4:20
Swarajya Pendharkar23-May-08 4:20 
QuestionWin32 Services Pin
scott.tiger16-Feb-07 4:31
scott.tiger16-Feb-07 4:31 
Will this code work to communicate between Win32 service and user application?

Regards,
Michael
AnswerRe: Win32 Services Pin
Swarajya Pendharkar17-Feb-07 2:34
Swarajya Pendharkar17-Feb-07 2:34 
GeneralRe: Win32 Services Pin
scott.tiger17-Feb-07 12:22
scott.tiger17-Feb-07 12:22 
GeneralRe: Win32 Services Pin
Swarajya Pendharkar17-Feb-07 19:45
Swarajya Pendharkar17-Feb-07 19:45 
GeneralRe: Win32 Services Pin
scott.tiger20-Feb-07 22:26
scott.tiger20-Feb-07 22:26 
GeneralRe: Win32 Services Pin
Swarajya Pendharkar20-Feb-07 22:50
Swarajya Pendharkar20-Feb-07 22:50 
GeneralRe: Win32 Services Pin
scott.tiger20-Feb-07 22:58
scott.tiger20-Feb-07 22:58 
GeneralRe: Win32 Services Pin
Swarajya Pendharkar20-Feb-07 23:32
Swarajya Pendharkar20-Feb-07 23:32 
GeneralRe: Win32 Services Pin
scott.tiger21-Feb-07 11:27
scott.tiger21-Feb-07 11:27 
GeneralRe: Win32 Services Pin
Swarajya Pendharkar21-Feb-07 19:00
Swarajya Pendharkar21-Feb-07 19:00 
GeneralRe: Win32 Services Pin
scott.tiger22-Feb-07 5:36
scott.tiger22-Feb-07 5:36 
GeneralRe: Win32 Services Pin
mabad6-Mar-07 0:01
mabad6-Mar-07 0:01 
GeneralRe: Win32 Services Pin
scott.tiger6-Mar-07 0:26
scott.tiger6-Mar-07 0:26 
Generalmy way of doing Pin
f225-Jun-06 4:17
f225-Jun-06 4:17 
GeneralRe: my way of doing Pin
Swarajya Pendharkar25-Jun-06 18:50
Swarajya Pendharkar25-Jun-06 18:50 
GeneralRe: my way of doing Pin
f226-Jun-06 1:17
f226-Jun-06 1:17 
GeneralRe: my way of doing Pin
Swarajya Pendharkar26-Jun-06 2:35
Swarajya Pendharkar26-Jun-06 2:35 
GeneralRe: my way of doing Pin
f226-Jun-06 16:10
f226-Jun-06 16:10 
GeneralRe: my way of doing Pin
Swarajya Pendharkar26-Jun-06 22:40
Swarajya Pendharkar26-Jun-06 22:40 
GeneralRe: my way of doing Pin
f227-Jun-06 3:51
f227-Jun-06 3:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.