c ++多线程:以递归方式调用终止

时间:2016-04-09 09:47:30

标签: c++ multithreading

我对C ++很陌生,已经参与了一个相当复杂的项目。该程序应该下载一个离线使用的网站。因此,为了简单起见,我所拥有的是一个"下载管理器"线程,创建尽可能多的"页面下载器"线程与下载页面一样。同样,还有一个分析线程树。以下是下载管理器的简化代码:

void DlPage::manageDownload(){
    bool end=false;
    unique_lock<mutex> dlLck(dlMtx); // dlMtx is part of the shared data
    vector<thread*> downloads;

    cerr << "Download manager : entering" << endl;
    try{
        dlLck.lock();
    }catch (int e){
        cerr << "Download Manager : unique_lock thrown exception: " << e << endl;
        exit(1);
    }
    cerr << "Download manager : mutex locked" << endl;

    while(!end){
        // wait for a new page to be available for dl
        cerr << "Download manager : downloading page " << pageId << endl;
        // preparing data structures for download
        downloads.push_back(new thread(pageDownload, /*args*/));
        end=/*end condition*/;
    }

    dlLck.unlock();
    cerr << "Download manager : mutex unlocked" << endl;

    for(i=0;i<downloads.size();i++){
        downloads[i]->join();
        delete downloads[i];
    }
    dbgStream() << "Download manager : exiting" << endl;
}

作为输出,我只是得到:

Download manager : entering
Analyse manager : entering // Analyse manager has the exact same structure as download.
Main : Program launched // First page is added to the shared data and both managers are warned

terminate called recursively // what I don't understand
Aborted

此时有主要的,以及它的2&#34;经理&#34;线程,在输出确认后成功创建。然后,锁定互斥锁,即使应该捕获任何异常,也会崩溃一切。而且,还有更多的错误信息会在这些情况下出现。根据我的理解,如果程序在退出函数时无法销毁每个对象,则会收到此消息。

感谢您的帮助,

Jglukn

1 个答案:

答案 0 :(得分:2)

这会锁定互斥锁:

unique_lock<mutex> dlLck(dlMtx);

这会尝试在同一个线程中再次锁定互斥锁,因为互斥锁已被锁定,因此会抛出异常:

try{
    dlLck.lock();
}catch (int e){
    cerr << "Download Manager : unique_lock thrown exception: " << e << endl;
    exit(1);
}

catch子句没有捕获正确的异常类型,因此异常传播给调用者,结果无法通过此处的代码确定。