posix标准信号灯(一般用于线程间通信)
同步:根据需求按照一定的顺序先后执行
API(posix标准信号灯(一般用于线程间通信))
1.sem_init:信号量初始化函数
函数原型:int sem_init(sem_t *sem, int pshared, unsigned int value);
sem:初始化的信号量
pshared:信号量共享的范围(0:线程间使用 非0:进程间使用)
value:信号量初值:如果是单核CPU,那么value的值给0或者1
2.sem_wait:P操作——申请资源
int sem_wait(sem_t *sem);
sem:信号量
返回值:
成功:0
出错:-1
3.sem_post:V操作——释放资源
int sem_post(sem_t *sem);
sem:信号量
返回值:
成功:0
出错:-1
锁:保护临界资源
4.pthread_mutex_init:初始化互斥锁
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
mutex:互斥锁
attr:互斥锁属性//NULL表示缺省属性
返回值:
成功:0
出错:-1
5.pthread_mutex_lock:申请互斥锁
int pthread_mutex_lock(pthread_mutex_t *mutex);
6.pthread_mutex_unlock:释放互斥锁
int pthread_mutex_unlock(pthread_mutex_t *mutex);
7.pthread_cond_init;初始化条件变量,在主进程中实现
int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr);
8.pthread_cond_wait;解锁(目的是让其他线程使用锁)、阻塞(不能先执行)、唤醒并且上锁、解锁,在后运行的线程中使用
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
9.pthread_cond_signal;发送条件变量,在先运行的线程中使用
int pthread_cond_signal(pthread_cond_t *cond);
同步:根据需求按照一定的顺序先后执行
API(posix标准信号灯(一般用于线程间通信))
1.sem_init:信号量初始化函数
函数原型:int sem_init(sem_t *sem, int pshared, unsigned int value);
sem:初始化的信号量
pshared:信号量共享的范围(0:线程间使用 非0:进程间使用)
value:信号量初值:如果是单核CPU,那么value的值给0或者1
2.sem_wait:P操作——申请资源
int sem_wait(sem_t *sem);
sem:信号量
返回值:
成功:0
出错:-1
3.sem_post:V操作——释放资源
int sem_post(sem_t *sem);
sem:信号量
返回值:
成功:0
出错:-1
锁:保护临界资源
4.pthread_mutex_init:初始化互斥锁
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
mutex:互斥锁
attr:互斥锁属性//NULL表示缺省属性
返回值:
成功:0
出错:-1
5.pthread_mutex_lock:申请互斥锁
int pthread_mutex_lock(pthread_mutex_t *mutex);
6.pthread_mutex_unlock:释放互斥锁
int pthread_mutex_unlock(pthread_mutex_t *mutex);
7.pthread_cond_init;初始化条件变量,在主进程中实现
int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr);
8.pthread_cond_wait;解锁(目的是让其他线程使用锁)、阻塞(不能先执行)、唤醒并且上锁、解锁,在后运行的线程中使用
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
9.pthread_cond_signal;发送条件变量,在先运行的线程中使用
int pthread_cond_signal(pthread_cond_t *cond);