bit*_*ise 9 c++ android mutex android-ndk
我正在尝试使用Android Native Development Kit进行多线程处理,因此我需要在C++端使用互斥锁.
使用Android NDK创建和使用互斥锁的正确方法是什么?
以下是我们如何使用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)
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)
| 归档时间: |
|
| 查看次数: |
12127 次 |
| 最近记录: |