Receive our weekly advanced programming tips for FREE
28.April
How to wotk with boost thread
0
| 0 votes
Autor: bookkeeper
Chapter: C++
Tags:
c++

If you don't know about Boost, when you should look at this. It's a huge collection of high performance libraries. One of them is Thread.

It's very easy to use.

The simplest way is:pp

#include <boost/thread/thread.hpp>
#include <iostream>

void func(){
 int i = 0;
 while(1){
    std::cerr << ++i;
    sleep(1);
 }
}

int main(){

 boost::thread t(func); // or boost::thread t = boost::thread(func)
 t.join();

 return 0;
}

It couldn't be simpler!

To compile: g++ -Wall -I/usr/include/boost/ -L/usr/local/lib/ -lboost_thread-gcc43 -o thread_boost thread_boost.cpp

Next step would be to use classes:

To use the class method in the thread you need boost::bind

#include <boost/thread/thread.hpp>
#include <iostream>
#include <boost/bind.hpp>

class ThreadClass{
public:
 ThreadClass(){}
 ~ThreadClass(){} 
void Run(){ while(1){ std::cerr << "tut" << std::endl; sleep(1); } }
void Run(int i){ while(1){ std::cerr << ++i << std::endl; sleep(1); } }

};
int main(){
 ThreadClass tc;

 boost::thread t1 = boost::thread( boost::bind(&ThreadClass::Run, &tc) );
 t1.join();

 return 0;
}

To use parameters just add one more parameter to bind:

boost::thread t2 = boost::thread( boost::bind(&ThreadClass::Run, &tc, 2) );

To compile: g++ -Wall -I/usr/include/boost/ -L/usr/local/lib/ -lboost_thread-gcc43 -o thread_boost thread_boost.cpp

The last thing is how to start a virtual method? You need to use boost::ref.

#include <boost/thread/thread.hpp>
#include <boost/bind.hpp> //<-- make it possible
#include <iostream>


class CBaseClass
{
  boost::thread t;
 public:
  CBaseClass(){}
  virtual ~CBaseClass(){};
  virtual void Function() = 0;
  void Start()
    {
      t = boost::thread( boost::bind( &CBaseClass::Function, boost::ref(*this) ) );
    }
  void Join(){ t.join(); }
};


class CChildClass : public CBaseClass
{

 public:
  CChildClass(){}
  virtual ~CChildClass(){}
  virtual void Function()
    {
        int c = 0;
 
         while(1)
         {
          std::cout << ++c << std::endl;
          sleep(1);
          if( c >= 7 )
           break;
         }
    }
};

int main()
{
 
 CChildClass some;
 some.Start();
 some.Join();
 
 return 0;
}

To compile: g++ -Wall -I/usr/include/boost/ -L/usr/local/lib/ -lboost_thread-gcc43 -o thread_boost thread_boost.cpp

Don't you love Boost? :)