Android NDK Mutex

bit*_*ise 9 c++ android mutex android-ndk

我正在尝试使用Android Native Development Kit进行多线程处理,因此我需要在C++端使用互斥锁.

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

mah*_*mah 9

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

  • 对后代的评论:我有一个使用pthread的应用程序,以及pthread互斥体,它运行正常,所以看起来它们已经实现,并且可以工作. (2认同)

Ser*_* K. 8

以下是我们如何使用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
};
Run Code Online (Sandbox Code Playgroud)

作为Linderdaum Engine的开发人员之一,我建议在我们的SDK中查看Mutex.h.


小智 6

#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);
}
Run Code Online (Sandbox Code Playgroud)


Jai*_*tes 5

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();
}
Run Code Online (Sandbox Code Playgroud)