An easy to use worker thread

Oct 31, 2001

2 min read

VC5

VC6

VC7.0

Win95

Win98

NT4

Win2K

VS6

C++

Windows

Visual-Studio

Dev

Intermediate

Author picture

by Frank Melber

Contributor

103k Views

Sample Image - WorkerThread.gif

Introduction

I had the need for a worker thread which is easy to use and is independent of libraries like MFC. So I wrote a class called CWorkerThread which fits my needs. It provides functionality to execute an unlimited amount of functions in a single thread. The functions are processed syncronously in the order the events which are related to these functions are fired.

How it works

The CWorkerThread class has a method called AddEvent(HANDLE hEvent, EVENTPROC pProc, LPVOID pProcParam = NULL); This function takes a handle, a static or global function and an optional void pointer. The function pProc is executed when the event hEvent occurs. The pProcParam parameter is passed to that function. You can call AddEvent(...) for all events you want the thread to process. To start the thread call the objects Start(const int& nPriority = THREAD_PRIORITY_NORMAL); method. This will create the thread and initialize it's event queue. When you now set an event, the related function will be executed. To give you an impression of this event queue I pasted the code of the threads "main" thread procedure here:

UINT CWorkerThread::ThreadProc(LPVOID pProcParam)
{
    assert(pProcParam);

    CWorkerThread* pThread = reinterpret_cast<CWorkerThread*>(pProcParam);
    DWORD dwResult = 0;

    int nSize = pThread->m_arrEvents.size();
    HANDLE* pArrEvents = new HANDLE[nSize];
    for (int i = 0; i < nSize; i++)
        pArrEvents[i] = pThread->m_arrEvents[i].hEvent;

    // Install the event queue...
    while (true)
    {
        dwResult = ::WaitForMultipleObjects(nSize,
                                            pArrEvents,
                                            FALSE,
                                            INFINITE) - WAIT_OBJECT_0;

        if (dwResult == WORKERTHREADEVENT_KILL)
            break;
		
        // Execute appropriate function...
        (pThread->m_arrEvents[dwResult].pProc)(
             pThread->m_arrEvents[dwResult].pProcParam);
    }

    delete[] pArrEvents;
	
    ::SetEvent(pThread->m_hEventIsKilled);
    return 0;
}

Conclusion

The supplied sample application will show you how it works. If you need help with this or have suggestions on how to improve it or state bugs, feel free to drop me an email. Updated versions may be found at http://www.nitrobit.com/ or http://www.codecommunity.com/.

License

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