c++ - 音频线程

标签 c++ multithreading audio

我的应用程序中有一个单独的音频线程,因为这在当时听起来是个好主意,但现在我很关心其他线程将如何与音频线程通信。

audioThread() {

while(!isCloseRequested) {

If(audio.dogSoundRequested) {

audio.playDogSound();
        }
    }
}

otherThread() {

Audio.dogSoundRequested();

}

这会是一种高效的线程音频方式吗?或者您认为此设置有问题吗?

最佳答案

这里的问题似乎是

1:如何使audio.dogSoundRequestedisCloseRequested 线程安全。

2:audioThread 正忙于等待(例如无限旋转直到 audio.dogSoundRequested 变为 true

正如其他人所建议的那样,您可以使用互斥锁来保护这两个变量,但这有点矫枉过正 - 此外,在音频代码中通常最好不要使用阻塞同步以避免 priority inversion 出现问题。 .

相反,假设您使用的是 C++11 或 C++14,您可以使用原子变量,它是轻量级的并且不会(在大多数实现中)阻塞:

#include <atomic>

...

std::atomic<bool> dogSoundRequested{false};
std::atomic<bool> isCloseRequested{false};

对 std::atomic 的读取和写入与内置类型具有相同的契约,但将生成代码以确保读取和写入相对于其他线程是原子的,并且结果与其他 CPU 同步.

audio.dogSoundRequested 的情况下,您需要这两种效果,而在 isCloseRequested 的情况下,结果在其他 CPU 上立即可见。

为了解决busy-waiting的问题,使用条件变量在有事要做的时候唤醒audioThread:

#include <condition_variable>

std::mutex m;
std::condition_variable cv;

audioThread() 
{
    while(!isCloseRequested) 
    {
        m.lock();
        cv.wait(m);

        // wait() returns with the mutex still held.
        m.unlock();
        if(audio.dogSoundRequested) 
        {
            audio.playDogSound();
        }
    }
}


void dogSoundRequested()
{
    dogSoundRequested = true;
    cv.notify_one();
}

关于c++ - 音频线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26680789/

相关文章:

c++ - Windows API的STL成员变量初始化问题

c++ - 检测函数类型是否为 noexcept 的特征

c++ - "const"在 C++ 中有多少和哪些用途?

C++ - 回到循环开始而不检查条件

java - 带线程的小程序执行不清楚

java - 哪些库可用于分析口语关键字和/或语音到文本的音频文件?

c# - 多个 View 共享相同的数据与多个线程之间的双向数据绑定(bind)

c++ - 如何在 x86 程序集中将当前线程的堆栈指针更改为新线程

python - 如何在python中加载m4a文件

Python PyAudio + 麦克风输入 - 特定频率滤波器?