- 在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());
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)
#include
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);