在Android ICS中,pthead库对应的路径为:
Android\bionic\libc\bionic\pthread.c
Android\bionic\libc\bionic\pthread-atfork.c
Android\bionic\libc\bionic\pthread-rwlocks.c
Android\bionic\libc\bionic\pthread-timers.c
Android\bionic\libc\bionic\pthread_internal.h
Android\bionic\libc\include\pthread.h
其中mutex在pthread.c中,相关的API有:
//pthread mutexattr 操作
int pthread_mutexattr_init(pthread_mutexattr_t *attr);
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type);
int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared);
int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared);
//pthread mutex 操作
int pthread_mutex_init(pthread_mutex_t *mutex,
const pthread_mutexattr_t *attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_timedlock(pthread_mutex_t *mutex, struct timespec* ts);
pthread_mutex_t对应一个结构体,包含一个int字段
typedef struct{ int volatile value;} pthread_mutex_t;
int字段分为5个部分,
/*
a mutex is implemented as a 32-bit integer holding the following fields
* * bits: name description
* 31-16 tid owner thread's kernel id (recursive and errorcheck only)
* 15-14 type mutex type
* 13 shared process-shared flag
* 12-2 counter counter of recursive mutexes
* 1-0 state lock state (0, 1 or 2)
*/
定义了一些macro来获得各个部分,其中mutex的type分为3类,有Normal, Recursive, Errorcheck,Recursize允许递归,Errorcheck会检测当前的状态。
#define MUTEX_OWNER(m) (((m)->value >> 16) & 0xffff)
#define MUTEX_COUNTER(m) (((m)->value >> 2) & 0xfff)
#define MUTEX_TYPE_MASK 0xc000
#define MUTEX_TYPE_NORMAL 0x0000
#define MUTEX_TYPE_RECURSIVE 0x4000
#define MUTEX_TYPE_ERRORCHECK 0x8000
#define MUTEX_COUNTER_SHIFT 2
#define MUTEX_COUNTER_MASK 0x1ffc
#define MUTEX_SHARED_MASK 0x2000
enum {
PTHREAD_MUTEX_NORMAL = 0,
PTHREAD_MUTEX_RECURSIVE = 1,
PTHREAD_MUTEX_ERRORCHECK = 2,
PTHREAD_MUTEX_ERRORCHECK_NP = PTHREAD_MUTEX_ERRORCHECK,
PTHREAD_MUTEX_RECURSIVE_NP = PTHREAD_MUTEX_RECURSIVE,
PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL
};
1 Mutex属性
pthread_mutexattr_t用来描述mutex的属性,
typedef long pthread_mutexattr_t;
属性包含了mutex的type,以及sharedflag。对应于mutex_t
* 15-14 type mutex type
* 13 shared process-shared flag
/* a mutex attribute holds the following fields
*
* bits: name description
* 0-3 type type of mutex
* 4 shared process-shared flag
*/
#define MUTEXATTR_TYPE_MASK 0x000f
#define MUTEXATTR_SHARED_MASK 0x0010
#define PTHREAD_PROCESS_PRIVATE 0
#define PTHREAD_PROCESS_SHARED 1
1.1 init和destory
init将type设置为Default,也就是Normal(0)也就是,type=Normal, shared 为Private
int pthread_mutex_init(pthread_mutex_t *mutex,
const pthread_mutexattr_t *attr)
{
int value = 0;
if (mutex == NULL)
return EINVAL;