2014-09-25 104 views
1

我希望創建一個擁有自己運行線程的類。我有以下代碼來測試開始一個新的線程。在C++類中運行線程

class SingletonClass 
{ 
public: 
    SingletonClass(); 
    virtual ~SingletonClass(){}; 

    static SingletonClass& Instance(); 
    void DoSomething(); 
private: 
    static void MyThread(std::string data); 

    std::thread m_thread; 
}; 

SingletonClass::SingletonClass() 
{ 
    m_thread = std::thread(MyThread, "test"); 
} 

void SingletonClass::MyThread(std::string data) 
{ 
    while(1) 
    { 
     std::cout<<data<<std::endl; 
    } 
} 

void SingletonClass::DoSomething() 
{ 
    std::cout<<"Hello"<<std::endl; 
} 

SingletonClass& SingletonClass::Instance() 
{ 
    static SingletonClass _instance; 
    return _instance; 
} 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
    SingletonClass& singleton = SingletonClass::Instance(); 
    singleton.DoSomething();  

    return 0; 
} 

當我運行我的程序線程函數被調用,然後該程序只彈了這個錯誤:

enter image description here

爲什麼會這樣呢?我怎樣才能獲得線程保留爲類實例化運行,只要

編輯

我在線程對象添加爲私有變量,並在構造函數中踢它關閉。它現在不會崩潰。

+0

只要單身人士還活着,你是否想保持你的線程運行,或者只要你的線程還活着,你想保持你的單身人士運行? – MatthiasB 2014-09-25 14:29:31

+0

可能是臨時的'std :: string'''test''生命期問題'。 – 2014-09-25 14:30:45

+0

我想保持它像單身人員一樣活着,當我擴展我的課程時我希望線程處理一些事情。 – 2014-09-25 14:31:40

回答

2

這是std::thread的析構函數做了什麼(§30.3.1.3[thread.thread.destr]):

~thread(); 

If joinable() , calls std::terminate() . Otherwise, has no effects. [ Note: Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable. —end note ]

SingletonClass構造函數創建的本地thread時構造退出,造成terminate()被銷燬被調用(默認情況下調用abort())。

一個可能的解決辦法是讓threadSingleton類的成員,並join它的Singleton析構函數(當然,如果你這樣做,你會需要一些方法來信號線程退出)。或者,您可以考慮在Singleton的構造函數中使用線程detach()

+0

請參閱我的編輯。我在線程對象中添加了一個私有變量,並在構造函數中將其踢出。它現在不會崩潰。你是男人:) – 2014-09-25 14:46:53

+1

你可以在析構函數中設置一個exit var,然後加入它 – paulm 2014-09-25 14:54:30