Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C++
Article

A small but effective discussion on threads - CxThread class !

Rate me:
Please Sign up or sign in to vote.
3.54/5 (22 votes)
14 Mar 20034 min read 98.2K   673   24   33
A small but effective discussion on threads , how they work , and tips and tricks ! Plus a cool implementation !

Introduction

There comes a time in every man's life when he has to survive a loop ! Let's say you want your user to select a folder and then you start scanning it for files . This can be a time consuming process and the user is not in the mood of seeing that the applications screen got ballistic . While searching he would like to be able to stop Search . This is a problem where we need multithreading or wisdom.

This is what wisdom says : Someone was asking how to continue processing messages for its application while working . That is a quite simple task . For those of you who used Visual Basic know of the life saving DoEvents() function . Well this here is its implementation in C/C++ !

Wisdom : DoEvents()

BOOL DoEvents()
{
    MSG msg;
    while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) == TRUE) 
    {
        if (GetMessage(&msg, NULL, 0, 0) ) 
        {
/*before you translate and dispatch you might consider
checking if that message does not close you window
you should ignore it because if you doevents() in a loop
and the user click the close buton it closes !
and you loop continues untill it ends .*/
            if((msg.message!=WM_DESTROY)&&(msg.message!=WM_CLOSE)&&
            ((msg.message!=WM_SYSCOMMAND)&&(msg.wParam!=SC_CLOSE)))
            {

                TranslateMessage(&msg);
                DispatchMessage(&msg);
/*for closing prevention !*/
            }
        }
        else
        { 
/*if all messages in queue processed we can return to our 
  time consuming operation*/
            return TRUE; 
        } 
}
return 0;
}

And the Multi-Threading way :

What is a thread ! In technical terms Microsoft Says :

A thread is basically a path of execution through a program. It is also the smallest unit of execution that Win32 schedules. A thread consists of a stack, the state of the CPU registers, and an entry in the execution list of the system scheduler. Each thread shares all of the process’s resources. A process consists of one or more threads and the code, data, and other resources of a program in memory. Typical program resources are open files, semaphores, and dynamically allocated memory. A program executes when the system scheduler gives one of its threads execution control. The scheduler determines which threads should run and when they should run. Threads of lower priority may have to wait while higher priority threads complete their tasks. On multiprocessor machines, the scheduler can move individual threads to different processors to “balance” the CPU load. Each thread in a process operates independently. Unless you make them visible to each other, the threads execute individually and are unaware of the other threads in a process. Threads sharing common resources, however, must coordinate their work by using semaphores or another method of interprocess communication.

I say this :

Imagine a program like a house with usually one room - the main thread . In this room you can have you living room . You need a bath in case you want to take a bath or after one day of hard work , you come home exhausted . On your way to your house you imagine yourself in the hot water relaxing . Making plans you park your car in front of the house and then with a silly smile of happiness on your face you go in with only one intention : get deep underwater . You call your wife : "Dear I'm home !" , no answer ! You are even happier thinking : "She's gone ! I'm gonna have some relaxation time for my own ! " With a feeling of relief you go in your room and grab a towel . You take your clothes off and wrap the towel around yourself . You go in the kitchen get a glass , pour some wine and you start moving towards the final destination singing . You open the door and you are shocked! : "Holly cow woman . What are you doing here !?!?"

This is what threads are really all about , you reach the worst conclusion of building another bath (thread) so you can take bath (execute) even if someone else is doing that (running) at that certain moment . BUT wait our story didn't end this way . The wife says : Care to join me ? Now our man fills with wisdom and uses the first technique of message peeking . He gets to run in the first thread , along with his wife , and still processes all messages from outside !

while(kids_not_home)
{
    take_hot_bath(wife_included);
}

This here is my thread class I wanted to share with you :

// Thread.h: interface for the CXThread class.
//
//////////////////////////////////////////////////////////////////////

    #if !defined(
        AFX_THREAD_H__BC1E1A60_2C98_4D0F_BA79_C1156C9BFFC3__INCLUDED_)
    #define AFX_THREAD_H__BC1E1A60_2C98_4D0F_BA79_C1156C9BFFC3__INCLUDED_

    #if _MSC_VER > 1000
    #pragma once
    #endif // _MSC_VER > 1000

#include <windows.h>

class CXThread
{
public:
    unsigned long GetRunTime();
/*The time in miliseconds sience the thread was started - 
  NOT THE CLASS CREATED*/
    unsigned long GetExitCode();
/*This returns the number the thread returns when it exits !
make sure it's not still running by using IsOver()*/
    bool IsOver();
/*IS the thread terminated*/
    bool IsRunning();
/*IS the thread still running*/
    bool Terminate(unsigned long exitCode=0);
/*force thread to close issueing the exitCode as exit code*/
    bool Suspend();
/*suspend thread execution - put thread to sleep
CAUTION :    THREADS CAN'T WAKE UP BY THEMSELVES !
        ONCE YOU PUT A THREAD TO SLEEP IT CAN'T ISSUE A 
        Resume() BY THEMSELVES*/
    bool Resume();
/*continue execution for sleeping threads*/
    bool Initiate(bool bSuspended=0);
/*this is the actual function that does the thread starting
  if suspended is true the thread is launched suspended 
  waiting for the wake up call*/
    CXThread();
    virtual ~CXThread();
protected:
/*this are overridable functions */
    virtual void ExitInstance();
/*this event occures when the thread is over , by it's own or helped :
what do I mean ? it ends normally ir it is killed - variable deletion*/
    virtual void InitInstance();
/*this event occures before the thread starts it's running - 
  variable initialisation*/
    virtual unsigned long ThreadFunction();
/*this is the actual thread body , you override with your class*/
private:
/*do not modify this in any way*/
    static unsigned long __stdcall Watcher(void * lpVoid);
    static unsigned long __stdcall ThreadBody(void * lpVoid);
    HANDLE hTh,hwTh;
    unsigned long wthID,thID,thsTime,theTime;
};

#endif
  //!defined(AFX_THREAD_H__BC1E1A60_2C98_4D0F_BA79_C1156C9BFFC3__INCLUDED_)

It's more than simple ! Now I think you want an example of some kind ! Go on reading.

Example

How to use each function :

#include "xthread.h"

class CDirSearch : public CDialog,CXThread
{
protected:
/**/
    unsigned long ThreadFunction();
    void ExitInstance();
    void InitInstance();
/**/


//the .cpp body part
unsigned long CDirSearch::ThreadFunction()
{
    ListDirectory(dir,"*.*",subdirs);
    return 1;
}

void CDirSearch::ExitInstance()
{
    m_OK.EnableWindow(1);
}

void CDirSearch::InitInstance()
{
    m_OK.EnableWindow(0);
}

History

  • Only release 3:47 PM 3/15/2003 (I think)

Last but not least

And if you did not understand anything look at the code . You can't miss it . You'll get it for sure !:~) The source code will reveal its darkest secrets to your mortal eyes by only looking at it . And I'll let you in on another little secret of mine . You can use the very ancient but long forgotten copy-paste technique if the complexity of the source code overwhelms you . And if you need more information check the holy book of software engineers , the forbidden MSDN . Many words of wisdom will be discovered within its dirty and dusty pages . And to find out the truth about our existence , humanity , universe and aliens mail me tomkat@rol.ro

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Romania Romania
I have been programming for the past 6 years in VBasic, Delphi, C, C++ .
I also have extended knowledge of webdesign (HTML, CSS, JavaScript, VBScript), webprogramming (PHP, ASP, ASP.NET (C#)) and database integration (mySql, MSSQL Server).
And when I`m not programming I`m working out or working on some personal projects .
Last but not least I`m looking for a project-based job in programming or webdesign .

Comments and Discussions

 
GeneralThanks Pin
Bruno Challier29-Jun-05 4:15
Bruno Challier29-Jun-05 4:15 
GeneralWith regret for my work I deleted my other articles ! Maybe my last post here ! Pin
TomKat16-Mar-03 11:21
TomKat16-Mar-03 11:21 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
Chris Maunder16-Mar-03 13:08
cofounderChris Maunder16-Mar-03 13:08 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
TomKat16-Mar-03 14:02
TomKat16-Mar-03 14:02 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
kewball16-Mar-03 14:38
kewball16-Mar-03 14:38 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
dog_spawn16-Mar-03 16:57
dog_spawn16-Mar-03 16:57 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
Ernest Laurentin16-Mar-03 19:20
Ernest Laurentin16-Mar-03 19:20 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
TomKat16-Mar-03 21:55
TomKat16-Mar-03 21:55 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
Mike_H17-Mar-03 3:02
Mike_H17-Mar-03 3:02 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
yafancoop17-Mar-03 4:43
yafancoop17-Mar-03 4:43 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
Mike_H17-Mar-03 5:43
Mike_H17-Mar-03 5:43 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
TomKat17-Mar-03 10:46
TomKat17-Mar-03 10:46 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
TomKat17-Mar-03 10:38
TomKat17-Mar-03 10:38 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
Mike_H17-Mar-03 11:13
Mike_H17-Mar-03 11:13 
GeneralRe: With regret for my work I deleted my other articles ! Maybe my last post here ! Pin
TomKat18-Mar-03 10:52
TomKat18-Mar-03 10:52 
GeneralGood work Pin
Fad B16-Mar-03 3:07
Fad B16-Mar-03 3:07 
QuestionDo you want a job? Pin
Bill SerGio, The Infomercial King15-Mar-03 22:02
Bill SerGio, The Infomercial King15-Mar-03 22:02 
AnswerRe: Do you want a job? Pin
Stephane Rodriguez.16-Mar-03 0:20
Stephane Rodriguez.16-Mar-03 0:20 
GeneralRe: Do you want a job? Pin
Mike_H16-Mar-03 2:28
Mike_H16-Mar-03 2:28 
GeneralRe: Do you want a job? Pin
Anna-Jayne Metcalfe16-Mar-03 7:18
Anna-Jayne Metcalfe16-Mar-03 7:18 
GeneralRe: Do you want a job? Pin
TomKat16-Mar-03 10:22
TomKat16-Mar-03 10:22 
GeneralRe: Do you want a job? Pin
peterchen16-Mar-03 22:22
peterchen16-Mar-03 22:22 
AnswerRe: Do you want a job? Pin
TomKat16-Mar-03 10:22
TomKat16-Mar-03 10:22 
GeneralWatcher Thread Pin
Ray T Romero15-Mar-03 13:43
Ray T Romero15-Mar-03 13:43 
GeneralRe: Watcher Thread Pin
Ray T Romero15-Mar-03 13:50
Ray T Romero15-Mar-03 13:50 
Forget what I asked about object, I read CObject instead of CDialog.

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.