ios - 核心音频渲染线程和线程信号
<p><p>iOS 是否有任何一种不包括锁定的非常低级别的条件锁定?</p>
<p>我正在寻找一种方法,在不使用锁的情况下从 Core Audio 渲染线程中发出等待线程的信号。我想知道是否存在像 Mach 系统调用这样的低级别的东西。</p>
<p>现在我有一个 Core Audio 线程,它使用非阻塞线程安全消息队列将消息发送到另一个线程。然后另一个线程每 100 毫秒拉取一次,以查看队列中是否有可用消息。</p>
<p>但这是非常初级的,时机也很糟糕。我可以使用条件锁,但这涉及到锁定,我希望在渲染线程之外保留任何类型的锁定。</p>
<p>我正在寻找的是让消息队列线程等待,直到 Core Audio 渲染线程向它发出信号。就像 pthread 条件一样,但没有锁定且没有立即上下文切换?我希望核心音频线程在消息队列线程被唤醒之前完成。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><h2>已更新</h2>
<p><code>dispatch_semaphore_t</code> 运行良好并且比 mach <code>semaphore_t</code> 更高效。使用调度信号量的原始代码如下所示:</p>
<pre><code>#include <dispatch/dispatch.h>
// Declare mSemaphore somewhere it is available to multiple threads
dispatch_semaphore_t mSemaphore;
// Create the semaphore
mSemaphore = dispatch_semaphore_create(0);
// Handle error if(nullptr == mSemaphore)
// ===== RENDER THREAD
// An event happens in the render thread- set a flag and signal whoever is waiting
/*long result =*/ dispatch_semaphore_signal(mSemaphore);
// ===== OTHER THREAD
// Check the flags and act on the state change
// Wait for a signal for 2 seconds
/*long result =*/ dispatch_semaphore_wait(mSemaphore, dispatch_time(dispatch_time_now(), 2 * NSEC_PER_SEC));
// Clean up when finished
dispatch_release(mSemaphore);
</code></pre>
<h2>原答案:</h2>
<p>您可以为此目的使用 mach <code>semaphore_t</code>。我编写了一个封装功能的 C++ 类:<a href="https://github.com/sbooth/SFBAudioEngine/blob/master/Semaphore.cpp" rel="noreferrer noopener nofollow">https://github.com/sbooth/SFBAudioEngine/blob/master/Semaphore.cpp</a> </p>
<p>无论您最终是使用我的包装器还是使用您自己的包装器,代码大致如下所示:</p>
<pre><code>#include <mach/mach.h>
#include <mach/task.h>
// Declare mSemaphore somewhere it is available to multiple threads
semaphore_t mSemaphore;
// Create the semaphore
kern_return_t result = semaphore_create(mach_task_self(), &mSemaphore, SYNC_POLICY_FIFO, 0);
// Handle error if(result != KERN_SUCCESS)
// ===== RENDER THREAD
// An event happens in the render thread- set a flag and signal whoever is waiting
kern_return_t result = semaphore_signal(mSemaphore);
// Handle error if(result != KERN_SUCCESS)
// ===== OTHER THREAD
// Check the flags and act on the state change
// Wait for a signal for 2 seconds
mach_timespec_t duration = {
.tv_sec = 2,
.tv_nsec = 0
};
kern_return_t result = semaphore_timedwait(mSemaphore, duration);
// Timed out
if(KERN_OPERATION_TIMED_OUT != result)
;
// Handle error if(result != KERN_SUCCESS)
// Clean up when finished
kern_return_t result = semaphore_destroy(mach_task_self(), mSemaphore);
// Handle error if(result != KERN_SUCCESS)
</code></pre></p>
<p style="font-size: 20px;">关于ios - 核心音频渲染线程和线程信号,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/20844429/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/20844429/
</a>
</p>
页:
[1]