Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android NDK Mutex

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?

like image 528
CuriousGeorge Avatar asked May 26 '11 20:05

CuriousGeorge


2 Answers

The NDK appears to have support for pthread mutexes. I've not made use of them myself.

like image 167
mah Avatar answered Sep 30 '22 18:09

mah


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.

like image 37
Sergey K. Avatar answered Sep 30 '22 20:09

Sergey K.