线程
- 在Linux下用pcb来模拟的,轻量级进程
- 操作系统cpu调度的一个基本单位
- 是一个程序的执行线路
- 创建一个线程
int pthread_create(pthread_t *thread, //ID
const pthread_attr_t *attr, //设置线程的属性,attr为NULL表⽰使⽤默认属性
void *(*start_routine) (void *), //函数地址NULL
void *arg); //入口函数携带的参数
- 线程终止
线程终止有三种方法
1. 从线程函数return。这种⽅法对主线程不适⽤,从main函数return相当于调⽤exit。
2.线程可以调⽤pthread_ exit终⽌⾃⼰。
void pthread_exit(void *value_ptr);
3.⼀个线程可以调⽤pthread_ cancel终⽌同⼀进程中的另⼀个线程。
int pthread_cancel(pthread_t thread); //取消一个执行中的线程
//成功返回0;失败返回错误码
- 线程等待
int pthread_join(pthread_t thread, //线程id
void **value_ptr //指向线程的返回值);
//成功返回0;失败返回错误码
- 线程分离
int pthread_detach(pthread_t thread);
//可以是线程组内其他线程对目标线程进行分离,也可以是线程自己分离:
pthread_detach(pthread_self());
线程同步于互斥
mutex(互斥量)
- 动态分配
int pthread_mutex_init(pthread_mutex_t *restrict mutex,//要初始化的互斥量
const pthread_mutexattr_t *restrict attr //NULL);
- 互斥量加锁和解锁
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
- 销毁互斥量
int pthread_mutex_destroy(pthread_mutex_t *mutex);
死锁产生的四个条件
1.互斥条件
2.不可剥夺条件
3.请求与保持
4.环路等待条件
条件变量函数
- 初始化
int pthread_cond_init(pthread_cond_t *restrict cond, //要初始化的变量
const pthread_condattr_t *restrict attr //NULL);
- 等待条件满足
int pthread_cond_wait(pthread_cond_t *restrict cond, //在这儿等待
pthread_mutex_t *restrict mutex); //互斥量
- 唤醒等待
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);
- 销毁
int pthread_cond_destroy(pthread_cond_t *cond)
posix信号量
- 初始化信号量
#include <semaphore.h>
int sem_init(sem_t *sem, int pshared,//0表示线程间共享,非零表示进程间共享
unsigned int value); //信号量初始化
- 等待信号量
int sem_wait(sem_t *sem)
- 发布信号量
int sem_post(sem_t *sem);
- 销毁信号量
int sem_destroy(sem_t *sem);
读写锁
- 初始化
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);
- 加锁与解锁
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
- 销毁
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);