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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With