Click here to Skip to main content
15,892,927 members
Articles / Desktop Programming / Win32

Simple Worker Thread Class

Rate me:
Please Sign up or sign in to vote.
3.07/5 (15 votes)
5 May 2009CPOL2 min read 40.4K   905   17   10
A simple worker thread class with Join and post thread message

Introduction

Many times we need to create worker threads and generally we want to wait in the main thread till all worker threads finish their execution, something similar to pthread’s pthread_join call. We want some notification on the completion of worker thread; check the status of the worker thread if it is still executing in thread function or finished, etc. Also sometimes we want to keep the worker thread alive even on completion of thread function so that we can resubmit a different job (typically in a thread pool). All these things can be done with event objects by managing their state to signalled non signaled, etc. It is difficult to manage such code using different event objects. I consolidated all this commonly used worker thread functionality in a basic implementation of WorkerThread class.

WorkerThread Class

WorkerThread is a basic implementation for worker thread with PostThreadMessage, Join, RegisterOnCompleteRoutine and thread execution status. It can be enhanced further for many other features but I want to keep the idea simple. Here my main focus is just to show how to use a PostThreadMessage for worker threads.

Using the Code

Using WorkerThread class in your existing application is very simple. You just need to add WorkerThread.cpp in your project and include WorkerThread.h where you want to use this class.

Add variables of WorkerThread class wherever you want to create a worker thread. Create a worker thread using Start() with an optional auto quit parameter (default is true) and to end the thread, use End() method. If auto quit parameter is true, there is no need to call End() method of WorkerThread class. Join() method will simply cause calling thread to wait till work thread finishes its execution. GetStatus() will let you know the current thread status (NotCreated, Created, Started, Restarted, Complete). ReExecute() method can be used only for non auto quit threads (created with false parameter in constructor) with different or same data (this can be further enhanced to avoid overwriting the data). RegisterOnCompleteRoutine() method can be used to register an optional routine that will be called on completion of thread function.

Below is the sample code to show the usage of the WorkerThread class:

C++
#include "stdafx.h"
#include "WorkerThread.h"

#define MAXCOUNT 5

DWORD WINAPI ThreadProc(void *param)
{
    int i = (int)param;
    //
    // your code
    //
    
    return 0;
}

DWORD WINAPI OnComplete(void *param)
{
    int i = (int)param;

    printf("OnComplete data = %d\n", i);

    return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    // Create few worker threads with autoQuit false
    WorkerThread workerThread[MAXCOUNT] = {false, false, false, false, false};

    // Register an optional completion routine
    workerThread[2].RegisterOnCompleteRoutine(OnComplete, (void *)1234);

    // Start all of them
    for (int i = 0; i < MAXCOUNT; ++i) {
        if (workerThread[i].Start(ThreadProc, (void *)i)) {
            printf("Started %d\n", i);
        }
    }

    for (int i = 0; i < MAXCOUNT; ++i) {
        if (workerThread[i].ReExecute((void *)i)) {
            printf("Restarted %d\n", i);
        }

    }

    for (int i = 0; i < MAXCOUNT; ++i) {
        workerThread[i].End();
    }

    // main thread will wait here, till all others finish.
    for (int i = 0; i < MAXCOUNT; ++i) {
        workerThread[i].Join();
    }

    return 0;
}        

Points of Interest

Note the dummy PeekMessage() call in starting of ThreadProc(), just for force creation of a message queue for our worker thread.

History

  • 5th May, 2009: Initial revision

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Oracle
India India
Working with Oracle. Using C/C++, VC++, MFC, STL, C#, Java etc. on various platform like Windows, Unix, Macintosh etc. from last 13+ years to convert various type of requirements into running software components. My core expertise is multithreaded desktop product and large scale enterprises software development.

Comments and Discussions

 
SuggestionRead more on PostThreadMessage Pin
Manish K. Agarwal26-Jun-13 23:07
Manish K. Agarwal26-Jun-13 23:07 
QuestionMy vote 5 Pin
Shlabh Sharma27-Sep-11 2:19
Shlabh Sharma27-Sep-11 2:19 
GeneralMy vote of 1 Pin
Mike O'Neill12-May-09 8:01
Mike O'Neill12-May-09 8:01 
GeneralRe: My vote of 1 Pin
Manish K. Agarwal12-May-09 18:17
Manish K. Agarwal12-May-09 18:17 
GeneralMy vote of 1 Pin
Rick York6-May-09 6:46
mveRick York6-May-09 6:46 
The article's body has practically nothing regarding the WorkerThread class. You briefly mention some of its methods with a tiny bit of sample code and that is all.

Articles are SUPPOSED to describe issues involved in the implementation and any implementation details or techniques of interest. Refer to this site's articles about how to right an article if you are in doubt. This article has none of that. In short, it is very very weak.

Maybe you have missed it but there are dozens if not hundreds of worker thread classes around and this article has given us no reason to choose this one instead of any other. Actually it has given us many reasons not to choose this class which makes this article useless and a waste of time to read, let alone write comments about.

Also - I would like to know who would vote a five for this article. They must be totally clueless.
GeneralRe: My vote of 1 Pin
Manish K. Agarwal7-May-09 18:50
Manish K. Agarwal7-May-09 18:50 
GeneralRe: My vote of 1 Pin
geoyar12-May-09 11:51
professionalgeoyar12-May-09 11:51 
GeneralMy vote of 1 Pin
Johann Gerell5-May-09 20:57
Johann Gerell5-May-09 20:57 
GeneralRe: My vote of 1 Pin
;l34jk5;lsjdkf;5-May-09 21:39
;l34jk5;lsjdkf;5-May-09 21:39 
GeneralRe: My vote of 1 Pin
Manish K. Agarwal5-May-09 23:52
Manish K. Agarwal5-May-09 23:52 

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.