iOS 是否有任何类型的非常低级别的条件锁,不包括锁定?
我正在寻找一种方法来从核心音频渲染线程内向等待线程发出信号,而不使用锁。我想知道是否可能存在像 Mach 系统调用这样的低级内容。
现在我有一个核心音频线程,它使用非阻塞线程安全消息队列将消息发送到另一个线程。然后,另一个线程每 100 毫秒拉一次以查看队列中是否有可用消息。
但这是非常初级的,而且时机也很糟糕。我可以使用条件锁,但这涉及锁定,并且我希望将任何类型的锁定排除在渲染线程之外。
我正在寻找的是让消息队列线程等待,直到核心音频渲染线程向它发出信号。就像 pthread 条件一样,但没有锁定并且没有立即上下文切换?我希望核心音频线程在消息队列线程被唤醒之前完成。
Updated
A dispatch_semaphore_t
工作良好且比机器更高效semaphore_t
。使用调度信号量的原始代码如下所示:
#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);
原答案:
你可以使用机器semaphore_t
以此目的。我编写了一个封装功能的 C++ 类:https://github.com/sbooth/SFBAudioEngine/blob/master/Semaphore.cpp https://github.com/sbooth/SFBAudioEngine/blob/master/Semaphore.cpp
无论您最终使用我的包装器还是使用您自己的包装器,代码都会大致如下所示:
#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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)