Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Boost Code example of throwing an exception between threads

Can someone please show a simple, but complete example of how one could use Boost exception library to transfer exceptions between thread by modifying the code below?

What I'm implementing is a simple multi-threaded Delegate pattern.

class DelegeeThread
{
public:
  void operator()()
  {
     while(true)
     {
       // Do some work

       if( error )
       {
         // This exception must be caught by DelegatorThread
         throw std::exception("An error happened!");
       }
     }
  }
};

class DelegatorThread
{
public:
  DelegatorThread() : delegeeThread(DelegeeThread()){}  // launches DelegeeThread
  void operator()()
  {
    while( true )
    {
       // Do some work and wait

       // ? What do I put in here to catch the exception thrown by DelegeeThread ?
    }
  }
private:
  tbb::tbb_thread    delegeeThread;
};
like image 486
sivabudh Avatar asked Sep 03 '09 15:09

sivabudh


1 Answers

I assumed you want the delegate to be executed asynchronously on a separate thread. Here is the example using boost threads and exceptions:

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

class DelegeeThread
{
public:
    void operator()( boost::exception_ptr& excPtr )
    {
        try
        {
            int counter = 0;
            while( true )
            {
                // Do some work

                if( ++counter == 1000000000 )
                {
                    throw boost::enable_current_exception( std::exception( "An error happened!" ) );
                }

            }
        }
        catch( ... )
        {
            // type of exception is preserved
            excPtr = boost::current_exception();
        }
    }
};

class DelegatorThread
{
public:
    DelegatorThread() : 
      delegeeThread( boost::bind( &DelegeeThread::operator(), boost::ref( delegee ), boost::ref( exceptionPtr ) ) )
      {
          // launches DelegeeThread
      }

    void wait()
    {
        // wait for a worker thread to finish
        delegeeThread.join();

        // Check if a worker threw
        if( exceptionPtr )
        {
            // if so, rethrow on the wait() caller thread
            boost::rethrow_exception( exceptionPtr );
        }
    }

private:
    DelegeeThread           delegee;
    boost::thread           delegeeThread;
    boost::exception_ptr    exceptionPtr;
};


int main () 
{
    try
    {
        // asynchronous work starts here
        DelegatorThread dt;

        // do some other work on a main thread...

        dt.wait();

    }
    catch( std::exception& e )
    {
        std::cout << e.what();
    }

    system("pause");
    return 0;
}
like image 72
Sly Avatar answered Sep 27 '22 16:09

Sly