Reputation: 4777
I wish to create a class that has its own running thread. I have the following code to test kicking off a new thread.
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;
}
When I run my program the thread function is called and then the program just bombs out with this error:
Why is this so? And how can I get the thread to keep running as long as the class is instantiated
EDIT
I have added in the thread object as a private variable and kicked it off in the constructor. It now doesnt crash.
Upvotes: 1
Views: 4060
Reputation: 137394
This is what std::thread
's destructor does (§30.3.1.3 [thread.thread.destr]):
~thread();
If
joinable()
, callsstd::terminate()
. Otherwise, has no effects. [ Note: Either implicitly detaching or joining ajoinable()
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 ]
The local thread
created in the SingletonClass
constructor is destroyed when that constructor exits, causing terminate()
to be called (which in turn calls abort()
by default).
A possible fix is to make thread
a member of the Singleton
class, and join
it in the destructor of Singleton
(obviously if you do this you'd need some way to signal the thread to exit). Alternatively, you can consider detach()
ing the thread in Singleton
's constructor.
Upvotes: 2