Click here to Skip to main content
15,065,044 members
Articles / Programming Languages / C++
Posted 14 Oct 2003


94 bookmarked

Synchronized multi-threading in C++ (No MFC!)

Rate me:
Please Sign up or sign in to vote.
3.59/5 (41 votes)
19 Apr 2007BSD4 min read
A C++ wrapper for Win32 multi-threading


Have you ever found multi-threading and thread synchronization difficult tasks in Win32? Then try these classes. Here I provide a small code library that will give you tools for creating multi-threaded applications in the C++ way, with out using MFC. If you have done multi-threading in Java and got fed up with the thread classes in MFC, you have come to the right place. Enough talking, I will take you right away through a step-by-step tutorial on using these classes.


You should be familiar with OOPs. You should also be familiar with terms like virtual functions, overriding, namespaces, exceptions etc. But you need not be a C++ guru.

Using the code

First, I will give you the list of header files you should include in the CPP file that use my thread classes:

#include <STRING>
using namespace std;

#include "ou_thread.h"
using namespace openutils;

The next step is to create a customized Thread class from the base Thread class that you find in ou_thread.h:

class MyThread : public Thread {
    int m_nCount;
    MyThread(int n,const char* nm) {
        m_nCount = n;
    void run() {
        for(int i=0;i<m_nCount;i++) {
            cout << getName().c_str() << ":" << i << endl;

If you have done thread programming in Java, the above class will look familiar. First we have inherited publicly from the Thread class and then we gave our own implementation to the run() function. The MyThread class we just created has a private integer variable which is used by the run() function to print out the thread's name that much time. The setName() and getName() functions are derived from the base class.

Now let us create a main() function to test the MyThread class:

int main() {
    Thread *t1 = new MyThread(15,"Thread 01");
    Thread *t2 = new MyThread(10,"Thread 02");
    try {
    }catch(ThreadException ex) {
  delete t1;
  delete t2;
  return 0;

Here we created two thread pointers pointing to MyThread objects.

The MyThread constructor takes two arguments, value of the counter variable and the thread name. Then we start both these threads by calling the start() function, which in turn calls our implementation of run(). If the low-level thread creation was not successful, then the try-catch block will handle that problem gracefully.

When you run this program, you will get output much like the following:

ThreThread 02:0
Thread 02:1
Thread 02ad 01:1
Thread 01:2
Thread 01:3
Thread 02:3
Thread 02:4
Thread 0ead 01:4
Thread 01:5
Thread 01:6
Thread 02:6
Thread 02:7
Thread read 01:7
Thread 01:8
Thread 01:9

Thread synchronization

You can see that thread2 is executing the run() function before thread1 has finished and both threads execute together to produce a confusing result. This can be more serious if both threads are accessing a critical resource like a database file at the same time. This problem can be solved by using a Mutex object.

A Mutex is a synchronization object that allows one thread mutually exclusive access to a resource. We can create a mutex using the Mutex class and hand over its ownership to the first thread. The next thread can be made to "wait" until the first thread "releases" the ownership of that object. Let us see how this can be achieved.

First include the following declaration to the main() function just before calling t1->start();

Mutex m("MyMutex");

This will create a mutex object identified by the name MyMutex. We can use this object in the run() function to control access to shared code. Modify the run() function in MyThread class to include calls to wait() and release() functions:

void run() {
        for(int i=0;i<m_nCount;i++) {
            cout << getName().c_str() << ":" << i << endl;

Please keep in mind that mutex names are case sensitive. If the mutex is not found, then wait() and release() functions will throw a ThreadException. Now recompile and run the program. You will see the following output:

Thread 01:1
Thread 01:2
Thread 01:3
Thread 01:4
Thread 01:5
Thread 01:6
Thread 01:7
Thread 01:8
Thread 01:9
Thread 01:10
Thread 01:11
Thread 01:12
Thread 01:13
Thread 01:14
Thread 02:0
Thread 02:1
Thread 02:2
Thread 02:3
Thread 02:4
Thread 02:5
Thread 02:6
Thread 02:7
Thread 02:8
Thread 02:9

You can see how thread2 waits until thread1 is finished, to produce the desired output. Using mutexes has their own overhead and tends to slow down everything. So use them when only one thread at a time should be allowed to modify data or some other controlled resource.

If synchronized by a mutex, it is important to call stop() on all threads in the same order start() was called on them. If no mutex was used, you can avoid calling stop() on threads.

Call the release() function of mutex after the calls to stop() functions of the thread objects.


Thread priority

Every thread has a base priority level determined by the thread's priority value and the priority class of its process. The system uses the base priority level of all executable threads to determine which thread gets the next slice of CPU time. Threads are scheduled in a round-robin fashion at each priority level, and only when there are no executable threads at a higher level does scheduling of threads at a lower level take place.

The setPriority() function enables setting the base priority level of a thread relative to the priority class of its process. This function can take any of the following values as its only argument:

Priority ValueMeaning
Thread::P_ABOVE_NORMALIndicates 1 point above normal priority for the priority class.
Thread::P_BELOW_NORMALIndicates 1 point below normal priority for the priority class.
Thread::P_HIGHESTIndicates 2 points above normal priority for the priority class.
Thread::P_IDLEKeeps this thread idle.
Thread::P_LOWESTIndicates 2 points below normal priority for the priority class.
Thread::P_NORMALIndicates normal priority for the priority class.
Thread::P_CRITICALPuts the thread in the highest possible priority.

For example, the following code puts thread1 in a high priority:


By default, a thread is created with the P_NORMAL priority.

Running the demo project

To run the demo project, create a Win32 console application in your Visual C++ IDE, add the demo project files to it and compile.


  • Created: October 14th, 2003
  • Updated source: 9 July 2004


This article, along with any associated source code and files, is licensed under The BSD License


About the Author

No Biography provided

Comments and Discussions

GeneralMy vote of 5 Pin
user55832085-Jul-13 23:46
Memberuser55832085-Jul-13 23:46 
GeneralMy vote of 5 Pin
zssure29-Aug-12 18:53
Memberzssure29-Aug-12 18:53 
GeneralMy vote of 5 Pin
zssure25-Aug-12 16:13
Memberzssure25-Aug-12 16:13 
QuestionQuick guide to make threads in C++ Pin
Jessn16-Jan-12 0:44
MemberJessn16-Jan-12 0:44 
GeneralThanks Pin
Member 442588920-Apr-10 11:02
MemberMember 442588920-Apr-10 11:02 
GeneralTwo error checks are always false Pin
cjdunford14-Nov-09 1:33
Membercjdunford14-Nov-09 1:33 
Questionunhandled exception in kernel32 0xE06D7363 on Thread::wait ( line "return false") Pin
barot7-May-09 11:21
Memberbarot7-May-09 11:21 
GeneralYou need to call CloseHandle after OpenMutex Pin
mgrcar21-Jul-07 13:31
Membermgrcar21-Jul-07 13:31 
QuestionRe: You need to call CloseHandle after OpenMutex Pin
maglev_tgv12-Nov-07 18:30
Membermaglev_tgv12-Nov-07 18:30 
I also got the same error.

Could you tell me how to handle this in more detail, please?

C++ Learner

GeneralRe: You need to call CloseHandle after OpenMutex Pin
Arash Moradinezhad20-Dec-07 8:25
MemberArash Moradinezhad20-Dec-07 8:25 
GeneralCompile error - cannot convert to LPCWSTR Pin
MEK35-Jun-07 21:14
MemberMEK35-Jun-07 21:14 
GeneralRe: Compile error - cannot convert to LPCWSTR Pin
AnOldGreenHorn6-Jun-07 18:01
MemberAnOldGreenHorn6-Jun-07 18:01 
GeneralRe: Compile error - cannot convert to LPCWSTR Pin
MEK37-Jun-07 21:53
MemberMEK37-Jun-07 21:53 
GeneralRe: Compile error - cannot convert to LPCWSTR Pin
embtech14-Jun-07 13:37
Memberembtech14-Jun-07 13:37 
GeneralRe: Compile error - cannot convert to LPCWSTR Pin
maglev_tgv19-Nov-07 19:11
Membermaglev_tgv19-Nov-07 19:11 
GeneralRe: Compile error - cannot convert to LPCWSTR Pin
jk2l30-Mar-08 14:48
Memberjk2l30-Mar-08 14:48 
QuestionCString to double conversion problem? Pin
Vinod Moorkkan19-Apr-07 21:41
MemberVinod Moorkkan19-Apr-07 21:41 
AnswerRe: CString to double conversion problem? Pin
frank.fang25-Apr-07 0:18
Memberfrank.fang25-Apr-07 0:18 
GeneralI get so many errors Pin
deville7523-Jan-07 3:20
Memberdeville7523-Jan-07 3:20 
GeneralRe: I get so many errors Pin
AnOldGreenHorn23-Jan-07 17:35
MemberAnOldGreenHorn23-Jan-07 17:35 
GeneralLinking Problem Pin
omerfarooqz16-Aug-06 6:18
Memberomerfarooqz16-Aug-06 6:18 
GeneralRe: Linking Problem Pin
AnOldGreenHorn16-Aug-06 17:30
MemberAnOldGreenHorn16-Aug-06 17:30 
GeneralBUG: CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)_ou_thread_proc,(Thread*)this,0,&tid) Pin
cp6633119-Aug-06 23:16
Membercp6633119-Aug-06 23:16 
GeneralRe: BUG: CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)_ou_thread_proc,(Thread*)this,0,&tid) Pin
AnOldGreenHorn10-Aug-06 17:57
MemberAnOldGreenHorn10-Aug-06 17:57 
GeneralThread fails if "stop" not called Pin
mcd9021-Apr-06 8:37
Membermcd9021-Apr-06 8:37 

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.