【发布时间】:2015-12-31 14:56:01
【问题描述】:
我有一个类,我想在线程中调用一个方法。
我的方法不会修改类属性,所以我希望它们是 const,但它们实例化了一个线程,所以它们不能。
在设置 std::thread 可变、由于线程而删除 const、编辑:或使用分离线程之间的最佳选择是什么?
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;
};
【问题讨论】:
-
您的哔哔声是如何工作的?如果它只是在给定的时间内发出哔哔声,也许更好的方法是分离线程,你不觉得吗?
-
BipParameter 包含 bips 的数量、持续时间以及每个 bips 之间的间隔 emitSound 使用这些参数调用蜂鸣器。
detach the thread是什么意思? -
auto t = std::thread(&ValidationSound::emitSound, this, std::cref(m_bipsParameters.second)); t.detach(); -
我通常建议不要使用分离线程。它们通常会导致讨厌的核心转储。
-
一种解决方案当然是使用不同的界面 - 创建一个线程,然后向该线程发送一条消息,该线程播放声音。如果消息队列只有一个槽,它将/应该阻塞,直到线程准备好接收下一条消息。
标签: c++ multithreading stl