Android NDK互斥锁

9

我正在尝试使用Android Native Development Kit进行一些多线程操作,因此我需要在C++端使用互斥锁。

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

4个回答

10

谢谢。我看到了一堆帖子说这个还没有实现,但它们可能已经非常过时了。我写了一个小的NDK模块,使用pthread编译通过了,但我从未尝试运行它。我能够在Java端进行线程处理。无论如何,还是谢谢,我可能最终会使用这个模块。 - CuriousGeorge
2
为了后人留言:我有一个应用程序正在使用pthread和pthread mutex,它运行良好,因此它们似乎已经被实现并且可以正常工作。 - Leif Andersen

9
以下是我们在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 的开发者之一,我建议您在我们的 SDK 中查看 Mutex.h。

9

这个问题已经有一段时间没有得到回答了,但我想指出的是,Android NDK现在支持C++11及以上版本,因此现在可以使用std::threadstd::mutex代替pthreads,以下是一个示例:

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

1
这是目前最好的、最跨平台的答案,应该排名更高。 - c.fogelklou

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接