Windows Thread Synchronization 29

 

 

 

More Critical Section Program Examples

 

Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.

 

More Critical Section Program Examples: Creating new Win32 C++ empty console application project

 

 

Then, add the source file and give it a suitable name.

 

More Critical Section Program Examples: Adding the C++ source file

 

Next, add the following source code.

 

// Program example which all the threads attempt to enter the critical section of code

// If they can not enter, they just printout that they are waiting to enter the critical section code.

 

#include <windows.h>

#include <stdio.h>

 

// Global variable

// The critical section object

CRITICAL_SECTION criticalSec;

 

///////////// Thread Main ///////////////////////

void ThreadMain(char *name)

{

        // Attempts to enter a critical section without blocking.

        // If the call is successful, the calling thread takes ownership of the critical section

        // If the critical section is successfully entered or the current thread already

        // owns the critical section, the return value is nonzero.

        // If another thread already owns the critical section, the return value is zero.

        if(TryEnterCriticalSection(&criticalSec) == 0)

            {

                  wprintf(L%S is waiting...\n, name);

            }

            else

            {

                  // critical section is mine...

                  wprintf(L%S in critical section, using shared resource...\n, name);

                  // Use the shared resource here...

 

                  // Releases ownership of the specified critical section object.

                  // Enabling another thread to become the owner and gain access to the protected resource

                  // The thread must call LeaveCriticalSection once for each time that it entered the critical section

                  // This function does not return a value.

                  wprintf(LLeaving the critical section...\n);

                  LeaveCriticalSection(&criticalSec);

        }

}

 

/////////////// Create A Child//////////////

HANDLE CreateChildTh(char *threadNum)

{

      HANDLE hThread;

      DWORD dwId;

 

    hThread=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadMain,(LPVOID)threadNum,0,&dwId);

 

      if(hThread != NULL)

      {

            wprintf(L\nCreateThread() is OK, thread ID %d\n, dwId);

            return hThread;

      }

      else

      {

            wprintf(LCreateThread() failed, error %d\n, GetLastError());

            return NULL;

      }

}

 

////////////////////Main (process & thread)////////////////////

int wmain(void)

{

    DWORD i;

    DWORD dwEvent;

    HANDLE hThread[7];

 

    wprintf(LInitializing the critical section...\n);

    InitializeCriticalSection(&criticalSec);

 

    hThread[0]=CreateChildTh(ChThread1);

    hThread[1]=CreateChildTh(ChThread2);

    hThread[2]=CreateChildTh(ChThread3);

    hThread[3]=CreateChildTh(ChThread4);

    hThread[4]=CreateChildTh(ChThread5);

    hThread[5]=CreateChildTh(ChThread6);

    hThread[6]=CreateChildTh(ChThread7);

  

    // Waits until one or all of the specified objects are

    // in the signaled state or the time-out interval elapses.

    dwEvent = WaitForMultipleObjects(7,hThread,TRUE,INFINITE);

 

      switch (dwEvent)

    {

        // hThread[0] was signaled

        case WAIT_OBJECT_0 + 0:

            // TODO: Perform tasks required by this event

            wprintf(LFirst event was signaled.\n);

            break;

 

        // hThread[1] was signaled

        case WAIT_OBJECT_0 + 1:

            // TODO: Perform tasks required by this event

            wprintf(LSecond event was signaled.\n);

            break;

 

        // hThread[2] was signaled

        case WAIT_OBJECT_0 + 2:

            // TODO: Perform tasks required by this event

            wprintf(LThird event was signaled.\n);

            break;

 

        // hThread[3] was signaled

        case WAIT_OBJECT_0 + 3:

            // TODO: Perform tasks required by this event

            wprintf(LFourth event was signaled.\n);

            break;

 

        // hThread[4] was signaled

        case WAIT_OBJECT_0 + 4:

            // TODO: Perform tasks required by this event

            wprintf(LFifth event was signaled.\n);

            break;

 

        // hThread[5] was signaled

        case WAIT_OBJECT_0 + 5:

            // TODO: Perform tasks required by this event

            wprintf(LSixth event was signaled.\n);

            break;

 

        // hThread[6] was signaled

        case WAIT_OBJECT_0 + 6:

            // TODO: Perform tasks required by this event

            wprintf(LSeventh event was signaled.\n);

            break;

 

        case WAIT_TIMEOUT:

            wprintf(LWait timed out...\n);

            break;

 

        // Return value is invalid.

        default:

            wprintf(LWait error %d\n, GetLastError());

            ExitProcess(0);

    }

  

      wprintf(L\n);

      for(i = 0;i<7;i++)

      {

            if(CloseHandle(hThread[i]) != 0)

                  wprintf(LhThread[%i] handle was closed successfully!\n, i);

            else

                  wprintf(LFailed to close the hThread[%i] handle! Error %d\n, i, GetLastError());

      }

 

      wprintf(LDelete the critical section...\n);

      DeleteCriticalSection(&criticalSec);

      return 0;

}

 

Build and run the project. The following screenshot is a sample output.

 

More Critical Section Program Examples: A sample console program output

 

 

 

< Thread Synchronization 28 | Thread Synchronization Programming | Win32 Programming | Thread Synchronization 30 >