SemaphoreExample: thread synchronisation using semaphores

Explains how to use Semaphores to achieve thread synchronization.

It is recommended to use semaphores instead of thread priorities for the following reasons:
  • In a uniprocessor environment, setting the thread priorities does not guarantee prioritized or serialized execution.

  • In a multiprocessor or SMP environment, thread priorities are irrelevant as multiple threads can run simultaneously.


Click on the following link to download the example:

Click: browse to view the example code.


The example creates a database containing a table of three columns with integer entries.

The example creates two threads:

  • WriterThread : This thread calls a periodic function at an interval of one second, and in each iteration it inserts one row of integers in the table.

  • ReaderThread : This thread also calls a periodic function at an interval of one second, and in each iteration it reads one row of integers following the last row read.

The example uses a macro USE_SEMAPHORE to show the difference between the code using semaphores and the code which doesn't use semaphores. When not using semaphores, it is not guaranteed that the ReaderThread will be able to read the database because in an SMP environment, data may not yet have been written by the WriterThread .

Using a semaphore serializes the thread execution. The read operation waits on the semaphore until it gets a signal from the write operation. This ensures that the ReaderThread only reads a row from the database after the WriterThread has written it.

Class summary

Building and configuring

To build the example:

  • The example builds an executable called semaphoreexample.exe in the standard location.

  • You can build the example from your IDE or the command line.

    If you use an IDE, import the bld.inf file of the example into your IDE, and use the build command of the IDE.

    If you use the command line, open a command prompt, and set the current directory to the source code directory of the example. You can then build the example with the SBSv1 build tools with the following commands:

    bldmake bldfiles

    abld build .

Running the example

The example code contains a macro USE_SEMAPHORE in the mmp file. By default it is commented out and on execution the example runs without using semaphores; the macro should be uncommented to use semaphores. The console output will generally look the same whether using semaphores or not if there is a single processor, but differences will occur in an SMP environment. Run the example following the instructions provided in the console.