std :: thread,在线程中引发异常会导致Visual C ++中出现中止错误

时间:2016-04-26 23:57:45

标签: c++ multithreading c++11 stdthread

我一直在尝试使用std:thread。我正在使用二进制表达式树进行标准算术运算。我正在创建一个线程来执行计算,并希望检查除以零。当线程以std::async启动时,从工作线程抛出异常并在主线程中捕获到正常。当我用std :: thread启动线程时,抛出异常时,我得到一个运行时错误,abort()。关于它为何与std::async but not std :: 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;

}

1 个答案:

答案 0 :(得分:3)

这是预期的行为:

请参阅std::thread documentation

  

线程在构造关联的线程对象时立即开始执行(等待任何OS调度延迟),从作为构造函数参数提供的顶级函数开始。顶级函数的返回值被忽略,如果通过抛出异常终止,则调用std :: terminate

请参阅std::async documentation

  

然后async在新的执行线程上执行函数f(所有线程局部变量已初始化),好像由std :: thread(f,args ...),生成,除非函数f返回一个值或抛出异常,它存储在共享状态,可通过std :: future访问,async返回给调用者。