Linux线程接口也称为pthread或POSIX线程,Linux2.6以后,采用Native POSIX线程库的新线程实现。
1, 互斥量
头文件<pthread.h> pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
静态分配:
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
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_trylock(pthread_mutex_t *mutex)
int pthread_mutex_unlock(pthread_mutex_t *mutex)
互斥量类型:
- 同一线程不应对同一互斥量加锁两次
- 线程不应对不为自己拥有的互斥量解锁
- 线程不应对一个尚未锁定的互斥量做解锁动作。
PTHREAD_MUTEX_NORMAL:不具有死锁检测功能,如线程试图对已由自己锁定的互斥量加锁,则发生死锁,互斥量处于未锁定状态,或者已由其他线程锁定,对其解锁会导致不确定的结果(在Linux上,对这类互斥量的上述两种操作都会成功)。
PTHREAD_MUTEX_ERRORCHECK:所有操作会执行错误检查,所有上述3种情况都会导致相关的函数返回错误,运行起来比一般要慢。
PTHREAD_MUTEX_RECURSIVE:递归互斥量维护一个计数器,加锁递增计数器,解锁递减计数器,为0时,释放该互斥量。
2,读写锁
<pthread.h>
int pthread_rwlock_init(pthread_rwlock_t *restict rwlock, const pthread_rwlockattr_t *restrict attr);
int pthread_rwlock_destroy(pthread_rwlock_t *restict rwlock);
int pthread_rwlock_rdlock(pthread_rwlock_t *restict rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *restict rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *restict rwlock);
3,条件变量
<pthread.h>
int pthread_cond_init(pthread_cond_t *restict cond, const pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_wait(pthread_cond_t *restict cond, pthread_mutex_t *restrict cond);
int pthread_cond_timedwait(pthread_cond_t *restict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict tsptr);
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
4,自旋锁
<pthread.h>
int pthread_spin_init(pthread_spinlock_t *lock,int pshared);
int pthread_spin_destroy(pthread_spinlock_t *lock);
int pthread_spin_lock(pthread_spinlock_t *lock);
int pthread_spin_trylock(pthread_spinlock_t *lock);
int pthread_spin_unlock(pthread_spinlock_t *lock);
5,屏障
屏障是用户协调多个线程并行工作的同步机制,允许每个线程等待,直到有合作的线程都到达某一点,然后从该点继续执行。
int pthread_barrier_init(pthread_barrier_t *restrict barrier, const pthread_barrierattr_t *restrict attr, unsigned int count)
int pthread_barrier_destroy(pthread_barrier_t *barrier)
int pthread_barrier_wait(pthread_barrier_t *barrier)