linux互斥锁,信号量等函数杂序

Linux下互斥锁、信号量
无论是互斥锁、自旋锁还是信号量,只有一个线程能够获得共享区域试用权。
#include<pthread.h>
初始化方式两种:
int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr)
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZE;
pthread_mutex_init(&mutex);
//请求上锁,阻塞,进行上下文切换
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);

//自旋锁,进行忙等,占用CPU资源,相对效率高一点
int pthread_spin_init(pthread_spinlock_t*lock,int pshared)
//请求上锁
int pthread_spin_lock(pthread_spinlock_t *lock);
int pthread_spin_unlock(pthread_spinlock_t *lock);

//信号量
编译使用:link with -lrt or -pthread
生产者和消费者模式,当生产者生产好发送信号告诉消费者来取走
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
int sem_post(sem_t *sem);
int sem_wait(sem_t* sem);
int sem_tryWait(sem_t* sem);
int sem_timedwait(sem_t* sem,const struct timespec* abs_times)

//线程
int pthread_create(pthread_t *thread,const pthread_attr_t *attr,void *(*start_routine)(void *),void *arg)


//条件变量:等待与信号发送
int pthread_cond_wait(pthread_cont_t *cptr,pthread_mutex_t *mptr)
int pthread_cond_signal(pthread_cond_t* cptr);
//唤醒多个线程
int pthread_cond_broadcast(pthread_cont_t *cptr)
int pthread_cond_timedwait(pthread_cont_t *cptr,pthrread_mutex_t *mptr,
const struct timespec *abstime)
struct timespec{
time_t tv_sev;
long tv_nsec;
}
互斥锁和条件变量主要是线程间同步,信号量可以是线程和进程间同步机制
信号量:有名信号量和无名信号量
有名信号量:
#include <semaphore.h>
sem_t *sem_open(const char *name,int oflag,/*mode_t mode,unsigned int value)
oflag:0、O_CREATE、O_CREATE|O_EXCL,如果O_CREATE则第三四参数指定,初次指定没错,若已存在,且指定O_CREATE|O_EXCL则报错
mode:指定权限位
value:指定信号量初始值,不能够超过SEM_VALUE_MAX(32767),
sem_wait
sem_post
int sem_close(sem_t* sem);
//进程终止,内核对其上打开的所以有名信号关闭,但并没有删除,


int sem_unlink(const char* name);
//将有名信号从系统中删除,可以是不同进程删除





猜你喜欢

转载自blog.csdn.net/liuhuashui123/article/details/54906724
今日推荐