I am trying to do some multithreading using the Android Native Development Kit, so I need a mutex on the C++ side.
What's the proper way to create and use a mutex with Android NDK?
The NDK appears to have support for pthread mutexes. I've not made use of them myself.
Here is how we go on Windows and Android (OS_LINUX define is for 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
};
As one of the developers of Linderdaum Engine i recommend checking out for Mutex.h in our SDK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With