Click here to Skip to main content
Click here to Skip to main content

Better threading

, 30 Jan 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
A more object-oriented way for multi-threading (not bound to MFC).

Sample Image - BetterThreading.jpg

Introduction

Have you noticed how often we ignore object-oriented concepts when doing even very simple multithreading? There are two typical examples:

  • You code a pure Win32 project in C++, and you just don't have time to devise some object-oriented thread API wrapper, so you simply create thread procedures here and there, eventually making the code unreadable.
  • You code an MFC application, and you need a worker thread. What do you do? Sure thing, you call AfxBeginThread, and (again) pass in a pointer to a thread procedure, ruining the object-oriented nature of the application.

Threads are fairly independent entities in an application, and as such, they must be separated from other implementations. The place where a thread procedure belongs least of all is a CDialog-derived class.

That's why I decided to make a thin wrapper class for a basic thread API. I use this class regularly, and I think it makes my applications better.

Using the Code

The code is actually a small class, Thread. Each instance of this class represents a thread, and the class contains some basic functions to control the thread, including gracefully (or ungracefully, if need be) terminating it.

Let's go through the steps necessary to set up a thread with this class:

  1. Derive a class from Thread. It will be the class that you later instantiate and use.
  2. Override the virtual function called ThreadProc. The implementation in your derived class is the substitution for a usual thread procedure. This virtual function must follow some basic rules to work properly. These are:
    • Never call _endthread, _endthreadex, ExitThread, and such from within ThreadProc. Instead, simply return.
    • From time to time (as often as possible), call GetStop to immediately clean up and return if GetStop returns true. See the example below.
  3. Instantiate Thread. Make sure you don't create it on the stack because the lifetime of the Thread object must be at least as long as that of the thread itself. A good place for a Thread-derived object is among members in some CWnd-derived class.
  4. Use the Thread::Start member function to start the thread. That's it!
  5. Optionally, you can control the thread from anywhere (including the thread procedure and your main thread) by calling its member functions.

Example of a good Thread-derived class:

class MyThread : public Thread
{
protected:
    virtual unsigned int ThreadProc()
    {
        void *pData = GetData(); //in case you'll need it

        for(int i=0; i<1000; ++i)
        {
            if(GetStop())
                return 0;
            Sleep(100); //some processing...

        }
        return 0;
    }
};

Some window class in your application could then have a member declared as follows:

protected:
    MyThread thread;

And finally, some member function of this class could call:

thread.Start(this);
//we're passing this pointer as additional data.

//This data could then be retrieved from within
//the thread by calling GetData()

See the demo application for more details.

Points of Interest

Note that the thread function is a non-static member of the Thread class. This is something you can't normally do because of the this pointer implicitly passed to non-static member functions. That's why ThreadProc gets called not directly, but through a mediator, _ThreadProc, which is a static class member. The rest of the implementation is pretty straightforward, and deserves no special explanation.

Disclaimer

Use this code at your own risk. Although I'm pretty sure it's safe, I still had to say this Big Grin | :-D

Happy coding!

Revision History

  • Jan 31, 2007 - Modified the demo application to eliminate SendMessage calls across threads.
  • Jan 30, 2007 - Originally posted.

License

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

Share

About the Author

Dennis Gourjii
Software Developer (Senior) Ramka Ltd.
Ukraine Ukraine
I'm a Software Developer / Architect from Kiev, Ukraine.
 
In the line of duty, I mostly use C/C++ (it's also by far my favorite) and C# (although it's a love-hate relationship).
 
I enjoy a challenging task to really make me scratch the back of my head every now and then.

Comments and Discussions

 
QuestionHow can I make this work ? Pinmembersodevrom15-Oct-08 3:36 
GeneralDelphi does it for years PinmemberCNemo753930-Jan-07 12:23 
GeneralRe: Delphi does it for years PinmemberDenis Gourjii30-Jan-07 12:39 
GeneralRe: Delphi does it for years PinmemberCNemo753930-Jan-07 15:25 
GeneralRe: Delphi does it for years PinmemberDenis Gourjii30-Jan-07 21:43 
GeneralUse of SendMessage() Across Threads Can Cause Deadlock PinmemberMike O'Neill30-Jan-07 7:48 
GeneralRe: Use of SendMessage() Across Threads Can Cause Deadlock PinmemberDenis Gourjii30-Jan-07 11:37 
GeneralRe: Use of SendMessage() Across Threads Can Cause Deadlock PinmvpHans Dietrich30-Jan-07 13:25 
GeneralRe: Use of SendMessage() Across Threads Can Cause Deadlock PinmemberDenis Gourjii30-Jan-07 21:46 
Generalzdorovenki buly Pinmembernoemailz30-Jan-07 6:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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
Web03 | 2.8.141223.1 | Last Updated 30 Jan 2007
Article Copyright 2007 by Dennis Gourjii
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid