声明
以下内容仅供学习,如有侵权,联系作者删除。
参考文献:B站up主:C语言技术网
链接: C语言技术网–高速缓存的实现
高速缓存
/*
* 高速缓存
* 作者:jack 日期:20210619
* 参考作者:C语言技术网(www.freecplus.net), B站UP主:C语言技术网
*/
#include <stdio.h>
#include <pthread.h>
#include<unistd.h>
#include <signal.h>
#include <string.h>
#include <vector>
using namespace std;
int mesgid = 1; // 消息的计数器
pthread_mutex_t mutex; // 声明互斥锁
pthread_cond_t cond; // 声明条件变量
// 缓存消息的结构体
struct st_message
{
int mesgid;
char message[1024];
}stmesg;
vector<struct st_message> vcache; // 用vector容器做缓存
// 消费者、出队线程主函数
void *outcache(void *arg)
{
// 增加线程清理函数,释放锁
struct st_message stmesg;
while(1)
{
pthread_mutex_lock(&mutex);
// 如果缓存为空,等待。
while(vcache.size() == 0) // 条件变量虚假唤醒
{
pthread_cond_wait(&cond, &mutex);
}
// 从缓存中获取第一条记录,然后删除该记录。
memcpy(&stmesg, &vcache[0], sizeof(struct st_message));
vcache.erase(vcache.begin());
pthread_mutex_unlock(&mutex);
// 以下是处理业务的代码
printf("pthid=%ld,,mesgid=%d\n", pthread_self(),stmesg.mesgid);
usleep(100); // 互斥锁优先唤醒
}
}
// 生产者、把生产者的数据存入缓存
void incache(int sig)
{
struct st_message stmesg;
memset(&stmesg, 0, sizeof(struct st_message));
pthread_mutex_lock(&mutex); // 加锁
// 生产数据,放入缓存
stmesg.mesgid = mesgid++; vcache.push_back(stmesg);
stmesg.mesgid = mesgid++; vcache.push_back(stmesg);
stmesg.mesgid = mesgid++; vcache.push_back(stmesg);
stmesg.mesgid = mesgid++; vcache.push_back(stmesg);
stmesg.mesgid = mesgid++; vcache.push_back(stmesg);
pthread_mutex_unlock(&mutex); // 解锁
//pthread_cond_signal(&cond); // 触发条件,激活排队中的第一个线程。
pthread_cond_broadcast(&cond); // 触发条件,激活全部的线程。
}
int main()
{
signal(15, incache); // 接收15的信号,调用生产者函数
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond,NULL);
pthread_t pthid1, pthid2, pthid3;
pthread_create(&pthid1, NULL, outcache, NULL);
pthread_create(&pthid2, NULL, outcache, NULL);
pthread_create(&pthid3, NULL, outcache, NULL);
pthread_join(pthid1, NULL);
pthread_join(pthid2, NULL);
pthread_join(pthid3, NULL);
return 0;
}