65.9K
CodeProject is changing. Read more.
Home

An easy to use worker thread

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.92/5 (6 votes)

Oct 31, 2001

1 min read

viewsIcon

102902

downloadIcon

1122

Use worker threads in your application without the complicated details

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/.