信号量与双缓冲

双缓冲

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <vector>
#include <iostream>
using namespace std;

vector<int> v1;
vector<int> v2;

sem_t semaphore;
unsigned int vectorSize = 5;
bool pushV1=true,pushV2=false;

pthread_mutex_t mutexV1,mutexV2;

void *producer(void */*arg*/)
{
int i=1,j=11;
while(1)
{
if(pushV1)
{
pthread_mutex_lock(&mutexV1);
v1.push_back(i);
cout << "push back vector1:" << i << ",size:" <<v1.size() << endl;
i++;
if(v1.size()>=vectorSize)
{
pushV1 = false;
pushV2 = true;
i = 1;
sem_post(&semaphore);
}
pthread_mutex_unlock(&mutexV1);
}else if(pushV2)
{
pthread_mutex_lock(&mutexV2);
v2.push_back(j);
cout << "push back vector2:" << j << ",size:" <<v2.size() << endl;
j++;
if(v2.size()>=vectorSize)
{
pushV2 = false;
pushV1 = true;
j = 11;
sem_post(&semaphore);
}
pthread_mutex_unlock(&mutexV2);
}
usleep(200*1000);
}
return 0;
}

void *consumer(void */*arg*/)
{
while (1)
{
sem_wait(&semaphore);
if(pushV2)
{
pthread_mutex_lock(&mutexV1);
if(v1.size()>0)
{
while(v1.size()>0)
{
int i = *v1.begin();
v1.erase(v1.begin());
cout << "vector1 pop:" << i <<",size:" << v1.size() << endl;
usleep(100*1000);
}
}
pthread_mutex_unlock(&mutexV1);
}else if(pushV1)
{
pthread_mutex_lock(&mutexV2);
if(v2.size()>0)
{
while(v2.size()>0)
{
int i = *v2.begin();
v2.erase(v2.begin());
cout << "vector2 pop:" << i <<",size:" << v2.size() << endl;
usleep(100*1000);
}
}
pthread_mutex_unlock(&mutexV2);
}
usleep(5*1000);
}
return 0;
}

int main()
{
pthread_t consumerThread,producerThread;

if(pthread_mutex_init(&mutexV1,NULL)!=0)
{
pthread_mutex_destroy(&mutexV1);
perror("init mutex fail");
}
if(pthread_mutex_init(&mutexV2,NULL)!=0)
{
pthread_mutex_destroy(&mutexV2);
perror("init mutex fail");
}
int res = sem_init(&semaphore, 0, 0);
if (res != 0)
{
perror("Semaphore initialization failed");
}
res = pthread_create(&consumerThread, NULL, consumer, NULL);
if (res != 0)
{
perror("Thread creation failure");
}
res = pthread_create(&producerThread, NULL, producer, NULL);
if (res != 0)
{
perror("Thread creation failure");
}
while (1)
{
sleep(5);
}
sem_destroy(&semaphore);
}


}

那些usleep请自己动态调整,我只是为了测试生产者生产快或消费者消费更快而写的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值