Android NDK Mutex

2019-01-26 08:03发布

问题:

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?

回答1:

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



回答2:

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.



回答3:

#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);
}


回答4:

It's been a while since this questions was answered, but I would like to point out that the Android NDK now supports C++11 and beyond, so it is now possible to use std::thread and std::mutex instead of pthreads, here's an example:

#include <thread>
#include <mutex>

int count = 0;
std::mutex myMutex;

void increment_count() {
    std::lock_guard<std::mutex> lock(myMutex);

    // Safely increment count
    count++

    // std::mutex gets unlocked when it goes out of scope
}

void JNICALL package_name_class_runMutexExample() {
    // Start 2 threads
    std::thread myThread1(increment_count);
    std::thread myThread2(increment_count);

    // Join your threads
    myThread1.join();
    myThread2.join();
}