Click here to Skip to main content
12,626,068 members (28,036 online)
Click here to Skip to main content
Add your own
alternative version


92 bookmarked

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

, 19 Apr 2007 BSD
Rate this:
Please Sign up or sign in to vote.
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 Value Meaning
Thread::P_ABOVE_NORMAL Indicates 1 point above normal priority for the priority class.
Thread::P_BELOW_NORMAL Indicates 1 point below normal priority for the priority class.
Thread::P_HIGHEST Indicates 2 points above normal priority for the priority class.
Thread::P_IDLE Keeps this thread idle.
Thread::P_LOWEST Indicates 2 points below normal priority for the priority class.
Thread::P_NORMAL Indicates normal priority for the priority class.
Thread::P_CRITICAL Puts 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

You may also be interested in...

Comments and Discussions

GeneralRe: An error when i add a sleep() in run() Pin
Vijay Mathew Pandyalakal22-Sep-05 18:40
memberVijay Mathew Pandyalakal22-Sep-05 18:40 
GeneralRe: An error when i add a sleep() in run() Pin
Surpaimb23-Sep-05 19:38
memberSurpaimb23-Sep-05 19:38 
GeneralAVOID to wait time-consuming tasks Pin
frank.fang25-Apr-07 1:04
memberfrank.fang25-Apr-07 1:04 
GeneralSequential in ATL Win Service Pin
Anonymous6-Aug-05 5:14
sussAnonymous6-Aug-05 5:14 
GeneralError adding to my project Pin
buho_usp2-Jun-05 10:15
memberbuho_usp2-Jun-05 10:15 
GeneralRe: Error adding to my project Pin
Vijay Mathew Pandyalakal2-Jun-05 18:49
memberVijay Mathew Pandyalakal2-Jun-05 18:49 
GeneralRe: Error adding to my project Pin
Anonymous4-Aug-05 13:47
sussAnonymous4-Aug-05 13:47 
Generalawesome! Pin
Sebastian Pipping24-Mar-05 11:33
memberSebastian Pipping24-Mar-05 11:33 
i'm currently working on an open source download manager
similar to flashget. you guess what i was looking for:
java-like socket and thread classes. right now it looks
like i'll take both from you. i've checked alot of
different packages including ZThreads, C++ Sockets
and Common C++ but they all didn't really fit my needs.
so i'm pretty happy you wrote these.

from your reply on the sockets i know you got work to do
but it in case you wanna join later just let me know.
i'd also like to know what your current job is about.
if you like to do some talking contact me through my website.

keep up the good work man!

best regards, sebastian pipping

ps: ou_thread.h really needs double inclusion protecion:

#ifndef __OU_THREAD_H__
#define __OU_THREAD_H__


#endif // __OU_THREAD_H__

don't forget to visit
Generalthread Pin
Anonymous7-Mar-05 21:18
sussAnonymous7-Mar-05 21:18 
GeneralSocket prog or threading Pin
Dablu4-Feb-05 2:19
memberDablu4-Feb-05 2:19 
GeneralRe: Bug - ExitThread() Pin
Vijay Mathew Pandyalakal25-Oct-04 2:32
memberVijay Mathew Pandyalakal25-Oct-04 2:32 
GeneralRe: Bug - ExitThread() Pin
Vijay Mathew Pandyalakal2-Jun-05 18:54
memberVijay Mathew Pandyalakal2-Jun-05 18:54 
GeneralUse WaitForSingleObject with caution! Pin
Volker von Einem20-Jul-04 21:11
memberVolker von Einem20-Jul-04 21:11 
GeneralRe: Use WaitForSingleObject with caution! Pin
Vijay Mathew Pandyalakal21-Jul-04 3:18
memberVijay Mathew Pandyalakal21-Jul-04 3:18 
GeneralRe: Use WaitForSingleObject with caution! Pin
bandanna2k14-Feb-07 7:46
memberbandanna2k14-Feb-07 7:46 
GeneralSo Good Pin
Hing14-Jul-04 17:03
memberHing14-Jul-04 17:03 
GeneralSlice of CPU time Pin
Pablez18-Feb-04 22:16
memberPablez18-Feb-04 22:16 
GeneralRe: Slice of CPU time Pin
John M. Drescher13-Jul-04 9:50
memberJohn M. Drescher13-Jul-04 9:50 
GeneralThe dinning philosopher's problem using threads Pin
ignacio nacho18-Feb-04 14:43
memberignacio nacho18-Feb-04 14:43 
GeneralRe: The dinning philosopher's problem using threads Pin
r.guerzoni13-Jul-04 3:42
memberr.guerzoni13-Jul-04 3:42 
GeneralThread Exit Pin
glove15-Oct-03 20:57
memberglove15-Oct-03 20:57 
GeneralRe: Thread Exit Pin
Nap16-Oct-03 15:18
memberNap16-Oct-03 15:18 
GeneralRe: Thread Exit Pin
glove16-Oct-03 16:36
memberglove16-Oct-03 16:36 
GeneralRe: Thread Exit Pin
Neville Franks17-Oct-03 2:55
memberNeville Franks17-Oct-03 2:55 
GeneralRe: Thread Exit Pin
Vijay Mathew Pandyalakal22-Sep-05 18:45
memberVijay Mathew Pandyalakal22-Sep-05 18:45 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.161205.3 | Last Updated 19 Apr 2007
Article Copyright 2003 by AnOldGreenHorn
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid