条件变量:了解了生产者消费者模型,我们来假设这样一个场景:你去超时买泡面可是发现货架是空的,生产者并没有提供任何口味的泡面,为了避免让顾客傻等,就需要条件变量来帮助我们。当有货物来的时候会通知你“有面了,快来买”。
类比到线程,同样当一个线程访问队列时,发现队列为空,它只能等待,直到其它线程将一个节点添加到队列当中。
条件变量相关函数:
(1)初始化:
pthread_cond_init (pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
cond:要初始化的条件变量
attr:NULL
(2)销毁条件变量
int pthread_cond_destroy(pthread_cond_t* cond);
(3)等待条件满足
int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);
第一个参数指向条件变量的指针,第二个参数指向互斥锁的指针。(为防止资源的竞争,条件变量总是和互斥锁协同使用)
(4)唤醒等待
int pthread_cond_broadcast(pthread_cond_t *cond);//唤醒集体
int pthread_cond_signal(pthread_cond_t *cond);//唤醒单个
利用单链表进行模拟生产者消费者场景
原理:利用两个线程来分别代表生产者和消费者,用单链表来表示中间的缓冲区
//创建节点结构
typedef struct ListNode
{
int data;
struct ListNode* _next;
}Node;
//构造节点
Node* creatNode(int data)
{
Node* newNode = (Node*)malloc(sizeof(Node));
if(newNode == NULL)
{
perror("malloc error\n");
return NULL;
}
newNode->data = data;
newNode->_next = NULL;
return newNode;
}
//初始化
void InitList(Node** head)
{
*head = creatNode(0);
}
//插入节点
void Push_head(Node* head,int data)
{
assert(head);
Node* newNode = creatNode(data);
newNode->_next = head->_next;
head->_next = newNode;
return;
}
//判空
int IsEmpty(Node* head)
{
assert(head);
if(head->_next == NULL)
{
return 0;
}
else
{
return 1;
}
}
//删除节点
void DelNode(Node* del)
{
assert(del);
free(del);
del = NULL;
return;
}
void Pop_head(Node* head,int *data)
{
assert(head);
if(IsEmpty(head) != 0)
{
Node* del = head->_next;
head->_next = del->_next;
*data = del->data;
DelNode(del);
return;
}
printf("List if Empty!\n");
return;
}
void DestroyList(Node* head)
{
assert(head);
Node* cur = head->_next;
while(cur)
{
Pop_head(head,NULL);
cur = cur->_next;
}
return;
}
//打印
void ShowList(Node* head)
{
assert(head);
Node* cur = head->_next;
while(cur)
{
printf("%d ",cur->data);
cur = cur->_next;
}
printf("\n");
return;
}
当生产者生产数据时,将新的数据放入单链表的头部;
void thread_producer(void *arg)
{
Node* head = (Node*)arg;
while(1)
{
sleep(1);
int data = rand()%100; //生成随机数
pthread_mutex_lock(&mutex);//加锁
Push_head(head,data);//放入数据
pthread_mutex_unlock(&mutex);//解锁
printf("Producer sell : %d\n",data);
pthread_cond_signal(&cond);//唤醒等待
}
return NULL;
}
当消费者消费数据时,将头部的数据弹出。
void* thread_consumer(void *arg)
{
Node* head = (Node*)arg;
while(1)
{
int data = 0;
pthread_mutex_lock(&mutex);
while(IsEmpty(head) == 0)//如果为空就等
{
pthread_cond_wait(&cond,&mutex);
}
Pop_head(head,&data);
pthread_mutex_unlock(&mutex);
printf("Consumer get : %d\n",data);
}
return NULL;
}
主函数:
int main()
{
Node* head;
InitList(&head);
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,thread_producer,(void*)head);//创建生产者线程
pthread_create(&tid2,NULL,thread_consumer,(void*)head);//创建消费者线程
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
运行结果:生产者生产一个,消费者消费一个,实现同步
[a@localhost list]$ ./test
Producer sell : 83
Consumer get : 83
Producer sell : 86
Consumer get : 86
Producer sell : 77
Consumer get : 77
Producer sell : 15
Consumer get : 15
信号量:
信号量:
POSIX信号量和SysremV信号量作用相同,都是用于同步操作,达到无冲突的访问共享资源目的。但POSIX可以用于线程间同步。
(1)初始化
#include<semaphore.h>
int sem_init(sem_t *sem,int pshared,unsigned int value);
参数:pshared:0表示线程间共享,非零表示进程间共享
value:信号量初始值
(2)销毁信号量
int sem_destroy(sem_t *sem);
(3)等待信号量
int sem_wait(sem_t *sem);//会将信号量的值减1
(4)发布信号量
sem_post(sem_t *sem);//表示资源使用完了可以归还资源了
数组和模运算来模拟环状结构
可以用信号量来实现生产者消费者同步,在下图中环有6个格子可以存放数据,生产者p负责放数据,消费者c负责拿数据。这6个格子可以循环利用。可以把其想成一个环形队列。
生产者与消费者在环形队列下需要遵循以下规则:生产者优先,消费者的永远不能追上生产者,生产者也不能超过消费者一圈。(可以想象成两个人赛跑)
代码实现:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<time.h>
#include<semaphore.h>
#define M 32
int ring[M];
sem_t semBlank;//空白格信号量
sem_t semData;//数据信号量
void *runP(void *arg)
{
int d;
int i = 0;
while(1)
{
sem_wait(&semBlank);//生产者等空白格子
ring[i] = rand()%1234+1;//生成随机数
i++;
i%=M;
printf("product done,data is:%d\n",d);
sem_post(&semData);//生产者放数据
}
}
void *runC(void *arg)
{
int d;
int i =0;
while(1){
sem_wait(&semData);//消费者等数据
d = ring[i];
i++;
i%=M;
printf("comsumer done,data is :%d\n",d);
sem_post(&semBlank);//消费者拿走格子上数据 格子还原为空白。
sleep(1);
}
}
int main()
{
sem_init(&semBlank,0,M);
sem_init(&semData,0,0);
srand((unsigned long)time(NULL));
pthread_t t1,t2;
pthread_create(&t1,NULL,runC,NULL);
pthread_create(&t2,NULL,runP,NULL);
sleep(1);
sem_destroy(&semBlank);
sem_destroy(&semData);
}
读写锁:
读写锁与互斥锁类似,不过读写锁允许更高的并行性。
读写锁的状态:(1)读模式下加锁状态(2)写模式下加锁状态(3)不加锁状态.
一次只有一个线程可以占有写模式的读写锁,但是多个线程可以同时占有读模式下的读写锁。
读写锁的行为:
读写锁也叫共享互斥锁,当读写锁是读模式锁住时,也认为是以共享模式锁住的,当它以写模式锁住时,可认为是以互斥模式锁住的。
读写锁在使用之前必须初始化,在释放他们底层内存之前必须销毁。
成功返回0,失败返回错误编号
要在读模式下锁定读写锁,需要调用pthread_rwlock_rdlock.
要在写模式下锁定读写锁,需要调用pthread_rwlock_wrlock.
不论在何种方式下锁住读写锁,都可以调用pthread_rwlock_wrlock.
pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
代码实现读写锁:
主函数:
int main()
{
pthread_rwlock_init(&rwlock,NULL);
int i = 0;
pthread_t t[8];
for(;i<3;i++)
{
pthread_create(t+i,NULL,t_write,(void*)i);
}
for(;i<8;i++)
{
pthread_create(t+i,NULL,t_read,(void*)i);
}
for(i = 0;i < 8;i++)
{
pthread_join(t[i],NULL);
}
pthread_rwlock_destroy(&rwlock);
}
如主函数中所设计的,读写锁非常适合于对于数据结构读的次数远大于写次数的情况,5个线程读,接着3个线程写。
结果: