我正在尝试使用Android Native Development Kit进行一些多线程操作,因此我需要在C++端使用互斥锁。
在Android NDK中创建和使用互斥锁的正确方法是什么?
我正在尝试使用Android Native Development Kit进行一些多线程操作,因此我需要在C++端使用互斥锁。
在Android NDK中创建和使用互斥锁的正确方法是什么?
NDK似乎支持pthread互斥锁,但我自己还没有使用过它们。
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
};
这个问题已经有一段时间没有得到回答了,但我想指出的是,Android NDK现在支持C++11
及以上版本,因此现在可以使用std::thread
和std::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();
}
#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);
}