我的应用程序中有一个单独的音频线程,因为这在当时听起来是个好主意,但现在我很关心其他线程将如何与音频线程通信。
audioThread() {
while(!isCloseRequested) {
If(audio.dogSoundRequested) {
audio.playDogSound();
}
}
}
otherThread() {
Audio.dogSoundRequested();
}
这会是一种高效的线程音频方式吗?或者您认为此设置有问题吗?
最佳答案
这里的问题似乎是
1:如何使audio.dogSoundRequested
和isCloseRequested
线程安全。
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/