2012-03-16 57 views
1

通过使用自旋锁和信号量来减少用户/内核切换,Windows CRITICAL_SECTION以比互斥体轻的方式实现(就锁/解锁性能而言)。线程同步@原生Android

即使互斥锁当前没有拥有/锁定,只有在旋转锁定的一段时间后才会请求CRITICAL_SECTION才会请求互斥锁(导致更好的性能),互斥锁需要上下文切换。

我是新来的Android本机开发,考虑Windows CRITICAL_SECTION,是否有一个相当于原生Android?

有什么比pthread_mutex_ 更轻的东西。 @ Android? 'pthread_mutex_ '强加一个上下文切换,即使该互斥量不是已拥有/锁定〜(如在Windows中)?

考虑快速进入/退出临界区段'pthread_mutex_ 的使用成本是多少?'强加?

是否有用户模式spinlock @ Native Android?

任何帮助将不胜感激。

Nadav在Sophin

+0

你对android设备锁定/解锁在本地层,即在c/c + +的任何想法。 – CoDe 2012-06-08 15:52:53

回答

4

没有,pthread_mutex_lock()在Android的仿生libc中不征收上下文切换为锁定一个正常的互斥无序状态 - 使用简单的原子比较和交换,然后是内存屏障。同样,如果没有进程在等待,则解锁互斥体不需要内核入口。

您可以在Bionic libc源代码中找到pthread_mutex_lock()pthread_mutex_unlock()的仿生实现,并自己查看。

一般来说,你可以考虑pthread_mutex_lock()/pthread_mutex_unlock()是相当轻量级。

3

以下是一些封装并行线程互斥成windows风格CRITICAL_SECTION

typedef struct tagCRITICAL_SECTION { 
    pthread_mutex_t  _mutex; 
    pthread_mutexattr_t _mutexattr; 
} CRITICAL_SECTION, *LPCRITICAL_SECTION; 


static inline 
VOID InitializeCriticalSection(LPCRITICAL_SECTION lpCriticalSection) { 
    // printf("[init] %0x\n", (UINT)lpCriticalSection); 
    int ret; 
    ret = pthread_mutexattr_init(&(lpCriticalSection->_mutexattr)); 
    assert(ret==0); 
#if defined (__APPLE__) || defined(__linux__) 
    pthread_mutexattr_settype(&lpCriticalSection->_mutexattr, PTHREAD_MUTEX_RECURSIVE); 
#elif ANDROID 
    // Do nothing 
#else 
    lpCriticalSection->_mutexattr.__mutexkind = PTHREAD_MUTEX_RECURSIVE_NP; 
#endif 
    ret = pthread_mutex_init(&(lpCriticalSection->_mutex), 
          &(lpCriticalSection->_mutexattr)); 
    assert(ret==0); 
} 

static inline 
VOID DeleteCriticalSection (LPCRITICAL_SECTION lpCriticalSection) { 
    int ret; 
    ret = pthread_mutex_destroy (&(lpCriticalSection->_mutex)); 
    assert(ret==0); 
    ret = pthread_mutexattr_destroy(&(lpCriticalSection->_mutexattr)); 
    assert(ret==0); 
} 

static inline 
VOID EnterCriticalSection  (LPCRITICAL_SECTION lpCriticalSection) { 
    int ret; 
    ret = pthread_mutex_lock(&(lpCriticalSection)->_mutex); 
    assert(ret==0); 
} 

static inline 
BOOL TryEnterCriticalSection  (LPCRITICAL_SECTION lpCriticalSection) { 
    int ret; 
    ret = pthread_mutex_trylock(&(lpCriticalSection)->_mutex); 

    return ret == 0; 
} 

static inline 
VOID LeaveCriticalSection  (LPCRITICAL_SECTION lpCriticalSection) { 
    int ret; 
    ret = pthread_mutex_unlock(&(lpCriticalSection->_mutex)); 
    // ret==1 means mutex is owned by another thread! 
} 
+0

这个实现非常方便,TnX!然而,它只是简单地包装aounf pthread互斥体而不实现自旋锁逻辑,Any1意识到用户模式自旋锁实现? – NadavRub 2012-03-16 11:53:02