Template Thread Library



Click here for a larger image.

Environment: Visual C++ 7.0, Windows XP sp1, Windows 2000 sp3

Abstract

This project demonstrates two non-MFC thread classes. One of them is a template library that can make any member function of any class execute in different threads, without the requirement of defining any static or global function. The other class requires inheritance in the same way that CWinThread under MFC works, but without any MFC dependency. Both classes use "_beginthreadex".

Details

First, the Template thread library takes in the constructor—a pointer to a class—and a point to one of its member functions. The member function must take no parameter and return void, as in the following:

class ThreadTest1
{
public:
  void InsideThread()
  {
    for(int i=0;i<5;i++)
    {
      cout << "ThreadTest1: " << i << endl;
    }
  }
};

This is a very simple class that has a single member function. To run this member in a different thread, use the TThread class, as follows:

ThreadTest1 test1;    //-- First, create an instance of the class
                      // that has the required member function --

  TThread<ThreadTest1> thTest1(test1,&ThreadTest1::InsideThread);
//-- The constructor takes two parameters and a third optional
// parameter; the first is an object of the class and the second
// is pointer to one of its member functions. The third optional
// parameter is the priority of the thread; the default is
// Normal --
  thTest1.StartAndWait();    //-- This member actually starts
                             // the thread and waits until the
                             // thread begins execution --
  thTest1.WaitUntilTerminate();    //-- Waits until the thread
                                   // terminates; optionally,
                                   // you can specify the number
                                   // of msec to wait --

The TThread class has a lot of member functions to increase and decrease the priority, terminate the thread immediately, and check the status of the thread.

Function Description
TThread The Constructor take three parameters. The first is an instance of a class that contains the member function that we want to run in a different thread. The second parameter is a pointer to the member function. The third one, which is optional, is the priority of the thread; the default is Normal.
WaitUntilTerminate Waits until the thread is terminated; also, you can define how many milliseconds to wait. The default is infinite. This member doesn't terminate the thread; if the thread didn't terminate at the specified number of msec, it will return false; otherwise, it will return true.
Start Starts the thread and returns immediately.
StartAndWait Starts the thread and waits until it begins executing.
Pause Suspends the thread. You need to call Start again to resume the thread.
IsRunning Returns true if the thread is running.
IsTerminated Returns true if the thread is terminated.
IsSuspend Returns true if the thread is suspended.
SetPriority and GetPriority Sets the priority to a specific value, or gets the current priority of the thread. The thread must be in running mode before calling any of these members.
SpeedUp Increases the thread priority to one step. The thread must be in running mode before calling any of these members.
SlowDown Decreases the thread priority to one step. The thread must be in running mode before calling any of these members.
Terminate Terminates the thread immediatly. Not Safe!!!

Second is the CThread class, which is a MFC-like CWinThread. You must overload the OnRunning method:

class ThreadTest2:public CThread
{
public:
  void OnRunning()
  {
    for(int i=0;i<5;i++)
    {
      cout << "ThreadTest2: " << i << endl;
    }
  }
};

Just create an instance of this class and call the Start() or the StartAndWait() method:

ThreadTest2 test2;

  test2.StartAndWait();    //-- This member actually starts the
                           // thread and waits until the thread
                           // begins execution --
  test2.WaitUntilTerminate();    //-- Waits until the thread
                                 // terminates; optionally, you
                                 // can specify the number of
                                 // msec to wait --

The other members of CThread are exactly like TThread.

Note: To pass any parameter to the thread, you just need to define a member variable to the thread class before calling the Start or StartAndWait member function, and you can use this variable inside the thread. Just make sure that no two threads access the same variable at the same time by using any locking technique.

Downloads

Download demo project - 130 Kb


Comments

  • Новый сервер Lineage 2 для новичков!

    Posted by Pumvedoreosse on 03/01/2013 03:10pm

    http://la2start.com/ - новый сервер Lineage 2 High Five для новичков! Заходите и присоединяйтесь! Лучшая игра всех времен! Мы только что открылись! Рейты х100 (крафт-пвп сервер)

    Reply
  • Can it receive message from main grogram?

    Posted by Legacy on 01/11/2004 12:00am

    Originally posted by: zeuss

    It's a non-MFC class library, so I think that it can't receive any windows message in the thread, right?
    If sometimes I want to signal something to the thread,
    how can I do for it? Just use global flags?
    Can any one give me a hint to do it.

    thanks

    zeuss

    Reply
  • It's an amazing project

    Posted by Legacy on 05/20/2003 12:00am

    Originally posted by: Rami

    I was searching for how can i make multithreading using C++ language, and your code really helped me a lot.

    It's written in a professional way and easy to use, keep going, you're doing an amazing work.

    Thanks a lot

    Reply
  • nice idea

    Posted by Legacy on 05/06/2003 12:00am

    Originally posted by: fatbone

    nice idea, can put a mmeber method of a class input another thread.

    Reply
  • Cool Idea

    Posted by Legacy on 04/28/2003 12:00am

    Originally posted by: Bharat Pallod

    This class definitely allows us to distribute resources in proper manner for different chunck of operations performed by some heavy class.

    That's great.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • The explosion in mobile devices and applications has generated a great deal of interest in APIs. Today's businesses are under increased pressure to make it easy to build apps, supply tools to help developers work more quickly, and deploy operational analytics so they can track users, developers, application performance, and more. Apigee Edge provides comprehensive API delivery tools and both operational and business-level analytics in an integrated platform. It is available as on-premise software or through …

  • Live Event Date: September 10, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild". This loop of continuous delivery and continuous feedback is …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds