Android NDK Mutex

我正在尝试使用Android本地开发工具包进行一些multithreading,所以我需要一个c ++端的互斥体。

用Android NDK创build和使用互斥锁的正确方法是什么?

谢谢

Solutions Collecting From Web of "Android NDK Mutex"

NDK似乎支持pthread互斥体 。 我自己并没有使用它们。

这里是我们如何去Windows和Android(OS_LINUX定义为Android):

class clMutex { public: clMutex() { #ifdef OS_LINUX pthread_mutex_init( &TheMutex, NULL ); #endif #ifdef OS_WINDOWS InitializeCriticalSection( &TheCS ); #endif } /// Enter the critical section -- other threads are locked out void Lock() const { #ifdef OS_LINUX pthread_mutex_lock( &TheMutex ); #endif #ifdef OS_WINDOWS if ( !TryEnterCriticalSection( &TheCS ) ) EnterCriticalSection( &TheCS ); #endif } /// Leave the critical section void Unlock() const { #ifdef OS_LINUX pthread_mutex_unlock( &TheMutex ); #endif #ifdef OS_WINDOWS LeaveCriticalSection( &TheCS ); #endif } ~clMutex() { #ifdef OS_WINDOWS DeleteCriticalSection( &TheCS ); #endif #ifdef OS_LINUX pthread_mutex_destroy( &TheMutex ); #endif } #ifdef OS_LINUX // POSIX threads mutable pthread_mutex_t TheMutex; #endif #ifdef OS_WINDOWS mutable CRITICAL_SECTION TheCS; #endif }; 

作为Linderdaum Engine的开发者之一,我build议在我们的SDK中检查Mutex.h。

 #include <pthread.h> class CThreadLock { public: CThreadLock(); virtual ~CThreadLock(); void Lock(); void Unlock(); private: pthread_mutex_t mutexlock; }; CThreadLock::CThreadLock() { // init lock here pthread_mutex_init(&mutexlock, 0); } CThreadLock::~CThreadLock() { // deinit lock here pthread_mutex_destroy(&mutexlock); } void CThreadLock::Lock() { // lock pthread_mutex_lock(&mutexlock); } void CThreadLock::Unlock() { // unlock pthread_mutex_unlock(&mutexlock); }