Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can initialising a thread in a class constructor lead to a crash?

I have not been able to determine where a strange crash is coming from, but the fact it's not happening deterministically makes me suspect threading.

I have something like this:

class MyClass
{
 MyClass() : mExit(false), mThread(&MyClass::ThreadMain,this)
 {}

 void ThreadMain()
 {
  unique_lock<mutex> lock(mMutex);
  mCondition.wait(lock, [&] { return mExit; });
 }

 std::thread mThread;
 std::mutex mMutex;
 std::condition_variable mCondition;
 bool mExit;
};

Obviously this is very simplified but I don't know for sure where the crash is happening yet so I want to ask if this setup can cause issues? What order is everything initialised for instance - is there a possibility ThreadMain can run before an instance of the class is fully constructed for example?

It looks like some examples I've seen online but I am not certain enough to say it's definitely safe or not.

like image 576
Mr. Boy Avatar asked Dec 10 '22 20:12

Mr. Boy


1 Answers

The only issue I see is that class members are initialized in the order they are declared in the class. Since mThread comes before all of the other class members it could be possible that the thread is using them before they are ever initialized.

To fix this you can rearrange the class members but I do not like this approach. If someone else comes along and changes the order it could break the code. You should be able to let the thread get default initialized and then start the thread in the constructor body because at that point all class members have been initialized.

like image 59
NathanOliver Avatar answered Dec 13 '22 11:12

NathanOliver