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);
//将有名信号从系统中删除,可以是不同进程删除





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值