synch: A C++ Multithreading Library

(full source available here)

Over the past few months I've written many programs in C++ that use threads. While there are many good threading packages out there (such as Boost Threads or pthreads), these libraries are not universally available and have different syntax in semantics in many cases. For example, porting an application that uses Win32 threads to Linux is difficult because all of the code for starting and synchronizing threads is different in Linux. Similarly, porting a program that uses Boost to a platform where Boost is not supported (or where you don't have administrative rights to install Boost) can often require an entire rewrite of the threading code.

To simplify porting, I've developed a small library called synch that exports several common synchronization primitives in a platform-independent manner. There are three implementations for synch: one based on Boost, one on pthreads, and one on the Win32 API. When developing a multithreading program with synch, you can use whatever implementation is hosted natively on your system. To port the application elsewhere, you can switch which of the three implementations you're using without having to rewrite the rest of your program.

One of the other advantages of using synch is that it provides a definition of a synchronized keyword in the style of Java. You can use synchronized like this:

    synch::Mutex mutex;
    synchronized (mutex) {
       cout << "This code executes while guarded by the mutex." << endl;

Other people have developed similar macros before (see this, for example), but it's still a nice feeling having built it myself without consulting any references.

Currently, synch supports threads and three synchronization primitives:

My main motivation behind synch is to support cross-platform threaded applications, so I hope to grow this list over time as I come up with new use cases.

The full C++ source for synch is freely available online, so don't hesistate to look over it, use it in your own applications, or offer feedback!