2015-06-03 50 views
0

以下是我的多線程程序。多線程程序,捕獲信號條件變量破壞

#include<csignal> 
#include<iostream> 
#include<string> 

void signalHandler(int signum) 
{ 
    std::cout<<"SigNum"<<signum; 

    exit(signum); 
} 

int main() 
{ 
    signal(SIGABRT, signalHandler); 
    signal(SIGINT, signalHandler); 
    signal(SIGSEGV, signalHandler); 
    Context context; 
    context.launch(); 
} 

上下文類是如下

class Context 
{ 
    private: 
    boost::condition_variable _conditionVariable; 

    public: 
    void launchThread1() 
    { 
    std::cout<<"Launch Thread1"; 
    /** Continuously and Asynchronously read data from the socket **/ 
    /** Act on the data, conditionVariable is involved   **/ 
    } 

    void launchThread2() 
    { 
    std::cout<<"Launch Thread2"; 
    /** Continuously and Asynchronously read data from the socket **/ 
    /** Act on the data, conditionVariable is involved   **/ 
    } 

    void launch() 
    { 
    boost::thread thread1(boost::bind(&Context::launchThread1,this)); 
    boost::thread thread2(boost::bind(&Context::launchThread2,this)); 

    std::cout<<"Joining Thread1"<<std::endl; 
    thread1.join(); 
    std::cout<<"Joining Thread2"<<std::endl; 
    thread2.join(); 
    } 
}; 

由於線程1連續運行,因此控制從未達到其中線程2可以連接到主線程的點。

因此印刷品是

Joining Thread1 

現在,一個信號SIGINT被拋出。當退出(正負號)被稱爲signalHandler,我得到以下錯誤

boost::condition_variable::~condition_variable(): Assertion `!pthread_mutex_destroy(&internal_mutex)' failed 
Segmentation Fault 

這是因爲線程2還沒有被加入到主線程?如果是,是否有一種方法可以明確停止signalHandler中的thread2?我必須讓線程成爲Context的數據成員嗎?這種方法有多安全?有沒有更好的方法來做到這一點?

回答

0

而不是退出(blah)這是通常皺眉,爲什麼不把原子標誌,並讓線程停止循環時,它被設置?然後在你的信號處理程序中設置標誌,線程自行停止,主要連接兩者,程序正常終止,所有析構函數都被調用等。

0

1 - 只要線程產生,您就立即退出主線程。你應該保持循環或等待線程重新加入。

2 - 在事件處理程序,只需設置一個布爾標誌來告訴線程退出

3 - 你的線程應該看看該變量和退出,如果爲真

如果變量只是一個布爾標誌,你不需要一個互斥體來保護它免受併發訪問

+0

有沒有像我可以使用的thread1.stop()函數? –

+0

我們都同時給出了相同的答案,但我認爲你的觀點1是錯誤的 - 他確實在等待加入。另外,爲了「好」,我更喜歡std :: atomic ,儘管你可能是正確的,它無論如何都會起作用。 –

+0

你只需要退出函數來「停止」線程 –