gpt4 book ai didi

线程间抛出异常的C++ Boost代码示例

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:27:27 25 4
gpt4 key购买 nike

有人可以通过修改下面的代码展示一个简单但完整的示例,说明如何使用 Boost 异常库在线程之间传输异常吗?

我正在实现的是一个简单的多线程委托(delegate)模式。

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;
};

最佳答案

我假设您希望委托(delegate)在单独的线程上异步执行。下面是使用 boost 线程和异常的示例:

#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;
}

关于线程间抛出异常的C++ Boost代码示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1374302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com