POSIX信号量
sem_t
sem_init()
int sem_init(sem_t *sem, int pshared, unsigned int value);
参数:pshared:0表⽰示线程间共享,⾮非零表⽰示进程间共享 value:信号量初始值
sem_wait() 条件不满足,等待
sem_post() 通知
sem_destroy()
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<semaphore.h>
#include<pthread.h>
sem_t producer;//notify producer
sem_t consumer;//notify consumer
int noodles = 1;
void *thr_producer(void *arg)
{
while(1)
{
sem_wait(&producer);
printf("make noodles\n");
noodles = 1;
sleep(1);
sem_post(&consumer);
}
return NULL;
}
void *thr_consumer(void *arg)
{
while(1)
{
sem_wait(&consumer);
printf("get noodles\n");
noodles = 0;
sleep(1);
sem_post(&producer);
}
return NULL;
}
int main()
{
pthread_t tid1,tid2;
sem_init(&producer, 0, 0);//0:
sem_init(&consumer, 0, 1);//0:一开始有一包面,在上面函数中就不用判断了
pthread_create(&tid1,NULL,thr_producer,NULL);
pthread_create(&tid2,NULL,thr_consumer,NULL);
pthread_join(&tid1,NULL);
pthread_join(&tid2,NULL);
sem_destroy(&producer);
sem_destroy(&consumer);
return 0;
}
读写锁
多应用于读多写少的情景
写独占,读共享,写锁优先级高
创建一个读写锁:pthread_rwlock_t rwlock;
初始化读写锁:pthread_rwlock_init(&rwlock,NULL);
加锁:
- pthread_rwlock_wrlock(&rwlock);
- pthread_rwlock_rdlock(&rwlock);
解锁:pthread_rwlock_unlock(&rwlock);
销毁:pthread_rwlock_destroy(&rwlock);
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<semaphore.h>
#include<pthread.h>
char *ptr = "i am blackboard";
pthread_rwlock_t rwlock;
void *thr_write(void *arg)
{
while(1)
{
pthread_rwlock_wrlock(&rwlock);
printf("draw blackboard\n");
sleep(2);
pthread_rwlock_unlock(&rwlock);
usleep(1000);
}
return NULL;
}
void *thr_read(void *arg)
{
int id = (int)arg;
while(1)
{
pthread_rwlock_rdlock(&rwlock);
sleep(1);
printf("public %d:read blackboard [%s]\n",id,ptr);
pthread_rwlock_unlock(&rwlock);
usleep(1000);
}
return NULL;
}
int main()
{
pthread_t tid1,tid2[2];
pthread_rwlock_init(&rwlock,NULL);
pthread_create(&tid1,NULL,thr_write,(void *)1);
pthread_create(&tid2[0],NULL,thr_read,(void *)2);
pthread_create(&tid2[1],NULL,thr_read,(void *)3);
pthread_join(&tid1,NULL);
pthread_join(&tid2[0],NULL);
pthread_join(&tid2[1],NULL);
pthread_rwlock_destroy(&rwlock);
return 0;
}