I have a class where I want to call a method in a thread.
My methods don't modify the class attributs so I expect them to be const, but they instantiate a thread, so they can't.
What is the best choice between putting the std::thread mutable, remove the const because of the thread, edit : or using detached threads ?
class ValidationSound
{
public:
[... CTOR DTOR ...]
void emitSuccessSoundAsync() const
{
if(m_thread.joinable())
{
m_thread.join();
}
m_thread = std::thread(&ValidationSound::emitSound, this, std::cref(m_bipsParameters.first));
};
void emitFailureSoundAsync() const
{
if(m_thread.joinable())
{
m_thread.join();
}
m_thread = std::thread(&ValidationSound::emitSound, this, std::cref(m_bipsParameters.second));
};
void emitSound(const BipParameters& bipParam) const
{
//BIP BIP THE BUZZER
};
private:
std::pair<BipParameters, BipParameters> m_bipsParameters;
mutable std::thread m_thread;
};
My methods don't modify the class attributs so I expect them to be const, but they instantiate a thread, so they can't.
But your methods do modify class attributes. Your std::thread is a class attribute and once any of your methods are called, that attribute will change (begin running) and continue to change state even after the methods have exited.
What is the best choice between putting the std::thread mutable, remove the const because of the thread, edit : or using detached threads ?
In this case, I'd recommend removing the const from method signatures. Const just confuses the interface and could fool users into thinking it's thread-safe. If the methods were mutex protected and blocked for the duration of the thread execution time, you could make a stronger argument for mutable and const, but given your current implementation I wouldn't.
Edit: Said another way, imagine you've gone ahead and created a single const instance of you ValidationSound class. It would be very easy for a user of this class to call your instance in a way that creates many threads all playing different sounds interleaved at different times. Is that how you'd envision a const instance of this class behaving? It's certainly not how I'd envision it looking purely at the interface.
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