1.互斥量:Mutex
a.用于互斥访问
b.类型:pthread_mutex_t,必须被初始化为PTHREAD_MUTEX_INITIALIZER(用于静态分配的mutex,等价于 pthread_mutex_init(…, NULL))或者调用pthread_mutex_init。Mutex也应该用pthread_mutex_destroy来销毁。
#i nclude <pthread.h>
1)
int pthread_mutex_init(
pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
函数 pthread_mutex_init用来生成一个互斥锁,NULL参数表明使用默认属性;
如果需要声明特定属性的互斥锁,须调用函数 pthread_mutexattr_init.
函数 pthread_mutexattr_setpshared 和函数 pthread_mutexattr_settype 用来设置互斥锁属性。前一个函数设置属性pshared,它有两个取值, PTHREAD_PROCESS_PRIVATE和PTHREAD_PROCESS_SHARED。前者用来不同进程中的线程同步,后者用于同步本进程的不同线程。
2)
int pthread_mutex_destroy(pthread_mutex_t *mutex);
3)
int pthread_mutex_lock(pthread_mutex_t *mutex);
4)
int pthread_mutex_trylock(pthread_mutex_t *mutex);
5)
int pthread_mutex_unlock(pthread_mutex_t *mutex);
2.Conditional Variable:条件
a.条件必须被Mutex保护起来
b.类型为:pthread_cond_t,必须被初始化为PTHREAD_COND_INITIALIZER(用于静态分配的条件,等价于pthread_cond_init(…, NULL))或者调用pthread_cond_init
#i nclude <pthread.h>
1)
int pthread_cond_init(
pthread_cond_t *restrict cond,
const pthread_condxattr_t *restrict attr)
2)
int pthread_cond_destroy(pthread_cond_t *cond);
3)
int pthread_cond_wait(
pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex);
4)
int pthread_cond_timedwait(
pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex,
const struct timespec *restrict timeout);
5)
int pthread_cond_signal(pthread_cond_t *cond);
6)
int pthread_cond_broadcast(pthread_cond_t *cond);