【问题标题】:mutable thread vs non-const method可变线程与非常量方法
【发布时间】: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(&amp;ValidationSound::emitSound, this, std::cref(m_bipsParameters.second)); t.detach();
  • 我通常建议不要使用分离线程。它们通常会导致讨厌的核心转储。
  • 一种解决方案当然是使用不同的界面 - 创建一个线程,然后向该线程发送一条消息,该线程播放声音。如果消息队列只有一个槽,它将/应该阻塞,直到线程准备好接收下一条消息。

标签: c++ multithreading stl


【解决方案1】:

我的方法不会修改类属性,所以我希望它们是 const,但它们实例化了一个线程,所以它们不能。

但是你的方法会修改类属性。您的 std::thread 是一个类属性,一旦调用了您的任何方法,该属性就会改变(开始运行)并且 continue 即使在方法退出后也会改变状态。

在设置 std::thread 可变、由于线程而删除 const、编辑:或使用分离线程之间的最佳选择是什么?

在这种情况下,我建议从方法签名中删除 const。 Const 只是混淆了界面,并可能欺骗用户认为它是线程安全的。如果这些方法在线程执行期间受到互斥保护并被阻塞,您可以为 mutable 和 const 提出更强的论据,但鉴于您当前的实现,我不会。

编辑:换一种说法,假设您已经继续并创建了一个 const 实例 ValidationSound 类。这个类的用户很容易以一种创建许多线程的方式调用您的实例,这些线程都在不同时间交错播放不同的声音。这就是你想象这个类的 const 实例的行为方式吗?这肯定不是我想象的纯粹从界面来看的方式。

【讨论】:

    猜你喜欢
    • 2013-01-07
    • 2014-10-18
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多