But*_*wis 2 c++ multithreading c++11 stdthread
我一直在尝试 std:thread。我使用二进制表达式树进行标准算术运算。我正在创建一个线程来执行计算并想要检查是否被零除。当线程以 启动时std::async,异常会从工作线程中抛出,并在主线程中很好地捕获。当我使用 std::thread 启动线程时,抛出异常时,我收到运行时错误abort()。关于它为什么与std::async but notstd::thread` 一起工作的任何见解?
// Declaration in the Expression.h file
public:
static long double __stdcall ThreadStaticEntryPoint(void * pThis);
long double __stdcall Expression::ThreadStaticEntryPoint(void * pThis)
{
long double calc;
Expression* pthrdThis = (Expression*)pThis;
calc = pthrdThis->Calculate();
return calc;
}
case 6:
try {
// Below works when encountering divide by zero.
// The thrown exception is caught correctly
// Launch thread using the this pointer
std::future<long double> fu = std::async(std::launch::async,
ThreadStaticEntryPoint, this);
calc = fu.get();
// When Creating a thread as below and I throw a divide by zero
// exception I get an error in visual C++. Below does not work:
//std::thread t1(&Expresson::Calculate, this);
//t1.join();
// Below works fine also
//calc = Calculate();
}
catch (runtime_error &r)
{
ShowMessage("LoadMenu() Caught exception calling Calculate()");
ShowMessage(r.what());
}
catch (...) {
ShowMessage("Exception caught");
}
long double Expresson::Calculate()
{
Expression *e;
long double calc = 0;
e = rep->GetExpression();
if (e == NULL)
{
ShowMessage("Main Expression " + to_string(rep->GetMainExpIndex()) + " is NULL. ");
return 0;
}
calc = e->Calculate()
return calc;
}
//************************************************************
// Calculate - Calculates Lval / Rval, returns result
//************************************************************
long double Divide::Calculate()
{
Expression* lop = this->getLOperand();
Expression* rop = this->getROperand();
long double Lval = 0, Rval = 0;
long double result = 0;
if (lop == NULL || rop == NULL)
return result;
Lval = lop->Calculate();
Rval = rop->Calculate();
//result = divides<long double>()(Lval, Rval);
// The throw error below causes the error
if (Rval == 0)
throw runtime_error("DivExp::Calculate() - Divide by zero exception occured. Rval = 0");
result = Lval / Rval;
return result;
}
Run Code Online (Sandbox Code Playgroud)
这是预期的行为:
线程在构造关联的线程对象后立即开始执行(等待任何操作系统调度延迟),从作为构造函数参数提供的顶级函数开始。顶级函数的返回值被忽略,如果它通过抛出异常而终止,则调用 std::terminate。
然后 async 在新的执行线程上执行函数 f(所有线程局部变量均已初始化),就像由 std::thread(f, args...) 生成一样,除非函数 f 返回值或引发异常,它存储在可通过 async 返回给调用者的 std::future 访问的共享状态中。
| 归档时间: |
|
| 查看次数: |
2364 次 |
| 最近记录: |