策略的更新、加载与同步

        C语言的C库提供了策略的更新、加载与同步的方法,这里引入多线程,达到区分读写任务(生产者——消费者 模型)的目的。

示例:

/*@brief check strategy to update, reload, synchronized to read(stoped by SIGINT)@author wen`xuanpei@email 15873152445@163.com(query for any question here)
*/
#include <pthread.h>//pthread_(create|exit), pthread_rwlock_(init|destroy|wrlock|rdlock|unlock),
#include <unistd.h>//sleep,
#include <errno.h>//<cerrno>//errno,
//stat
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>//<csignal>//sig_atomic_t,signal, SIG.+,
#include <stdio.h>//<cstdio>//fopen/fclose,perror,fread/fwrite,size_t,NULL,printf,
#include <stdlib.h>//<cstdlib>//abort,calloc,free,
#include <string.h>//<cstring>//memset,strlen,
#include <time.h>//<ctime>//time_t,/*define and select a strategy file type here*/
#define FORMAT_UNKNOWN (0)
#define FORMAT_XML (1)
#define FORMAT_JSON (2)
#define FORMAT_INI (3)
#if 0
#   define STRATEGY_FORMAT FORMAT_XML
#elif 0
#   define STRATEGY_FORMAT FORMAT_JSON
#elif 1
#   define STRATEGY_FORMAT FORMAT_INI
#else
#   define STRATEGY_FORMAT FORMAT_UNKNOWN
#endif
/*auto concate for strategy file path*/
#define concate(x, y) x y//
#if STRATEGY_FORMAT == FORMAT_XML
#   define STRATEGY_SUFFIX ".xml"
#elif STRATEGY_FORMAT == FORMAT_JSON
#   define STRATEGY_SUFFIX ".json"
#elif STRATEGY_FORMAT == FORMAT_INI
#   define STRATEGY_SUFFIX ".ini"
#else//FORMAT_UNKNOWN
#   define STRATEGY_SUFFIX ".txt"
#endif
#define STRATEGY_FILE concate("/tmp/strategy", STRATEGY_SUFFIX)
#define STRATEGY_FILE_MAX_SIZE _IO_BUFSIZ
#define thread_failed(s, msg) \
do{ \errno = s, perror(msg); \abort(); \
}while(0)/*to stop the update-thread and main-thread:by user signal SIGINTnotice:to keep data consistence of thread access, don't optmize to cache    */
static volatile int stop = 0;
static void handle_exception(sig_atomic_t sig){signal(sig, SIG_IGN);stop = 1;
}
/*exception protection:shadow other signals except SIGINT(SIGKILL,SIGSTOP is special)*/
static void shadow_exception(){sig_atomic_t sig;for(sig = 1; sig <= 64; sig++){if(sig == SIGINT)continue;if(sig > 31 && sig < 34)continue;signal(sig, SIG_IGN);}
}/*to load and update strategy file:by the latest update time(content modification or fresh time only)*/
static time_t latestUpdate;
/*to minimized lock conflict:split reader and writer*/
static pthread_rwlock_t rwLock;
/*to keep integrity of strategy file data:by lock and swap pointer(minimized lock conflict)*/
static char *strategyContent/* = NULL */;
static char *strategyContentBak/* = NULL */;
/*to make more concurrency of reader, copy a strategy self, use it without lock conflict*/
static char *strategyContentCopy/* = NULL*/;//improve performance(for reader)
/*@brief swap for any type of pointer@parama: pointer1(the length is the same as size_t)b: pointer2(the length is the same as size_t)@problem solved(user may be interested in it)convert failed for rvalue(expression) can't be write:(size_t)strategyContent ^= (size_t)strategyContentBakso, write as follows:get address => convert address type => dereference(access momory forcely)*(size_t*)&strategyContent    ^= *(size_t*)&strategyContentBak; 
*/
#define swap_pointer(a, b) _swap_pointer((size_t*)&a, (size_t*)&b)//wrapper for use it easily!!!
static void _swap_pointer(register size_t *a, register size_t *b){*a ^= *b;*b ^= *a;*a ^= *b;
}
/*swap strategy file buffer*/
static void swap(){int s;if( (s = pthread_rwlock_wrlock(&rwLock)) )thread_failed(s, "pthread_rwlock_wrlock");
#ifndef NDEBUG/*for view of debug*/printf("\nuser update the strategy file now!\n");        
#endifswap_pointer(strategyContent, strategyContentBak);pthread_rwlock_unlock(&rwLock);
}
/*reload and update strategy file*/
static void reload(time_t currentUpdate){FILE *fp = NULL;latestUpdate = currentUpdate;if( (fp = fopen(STRATEGY_FILE, "r")) ){memset(strategyContentBak, 0, sizeof(char) * STRATEGY_FILE_MAX_SIZE);//keep clean for textfread(strategyContentBak, sizeof(char), STRATEGY_FILE_MAX_SIZE, fp);fclose(fp), fp = NULL;swap();}else{perror("fopen");abort();}
}
/*update-thread:check if file is freshed, then reloadexcecption protection:after remove strategy file  */
static void *update(void* args){struct stat fbuf;time_t currentUpdate = 0;while(!stop){if(-1 == stat(STRATEGY_FILE, &fbuf) ){perror("stat");//to get position, __FILE__,__FUNCTION__,__LINE__ may be usedgoto __next_round;//avoid fresh the screen frequently}currentUpdate = fbuf.st_mtime;if(currentUpdate > latestUpdate)reload(currentUpdate);
__next_round:sleep(4);}
#ifndef NDEBUG/*for view of debug*/printf("\nupdate-thread exit now!\n");
#endifpthread_exit(NULL);
}/*allocate and deallocate for system resource*/ 
static char hasInit/* = 0*/;
static void init(){int s;pthread_t tid;signal(SIGINT, handle_exception);if( (s = pthread_create(&tid, NULL, update, NULL)))thread_failed(s, "pthread_create");if( (s = pthread_rwlock_init(&rwLock, NULL)) )thread_failed(s, "pthread_rwlock_init");if( !(strategyContent = calloc(sizeof(char), STRATEGY_FILE_MAX_SIZE) ) ){perror("calloc");abort();}if( !(strategyContentBak = calloc(sizeof(char), STRATEGY_FILE_MAX_SIZE) ) ){perror("calloc");abort();}if( !(strategyContentCopy = calloc(sizeof(char), STRATEGY_FILE_MAX_SIZE) ) ){perror("calloc");abort();}hasInit = 1;
}
static void destroy(){if(hasInit){pthread_rwlock_destroy(&rwLock);free(strategyContent), strategyContent = NULL;free(strategyContentBak), strategyContentBak = NULL;free(strategyContentCopy), strategyContentCopy = NULL;}
}/*compatible for multi-thread shared read:read and use the strategy file*/
static int readCount/* = 0 */;
static void read_use(){int s;if( (s = pthread_rwlock_rdlock(&rwLock)) )thread_failed(s, "pthread_rwlock_rdlock");memcpy(strategyContentCopy, strategyContent, STRATEGY_FILE_MAX_SIZE * sizeof(char));pthread_rwlock_unlock(&rwLock);printf("\n>>>%dth read strategyContent:\n", ++readCount);//CLIfwrite(strategyContent, sizeof(char), strlen(strategyContent), stdout);
}/*prepare strategy file for test*/
static void prepare(){
#if STRATEGY_FORMAT == FORMAT_XML//.xmlsystem("echo \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\"   >" STRATEGY_FILE ";""echo \"<root>\"                         >>" STRATEGY_FILE ";""echo \"\t<strategy>\"                   >>" STRATEGY_FILE ";""echo \"\t\t<person>\"                   >>" STRATEGY_FILE ";""echo \"\t\t\t<name>john</name>\"        >>" STRATEGY_FILE ";""echo \"\t\t\t<age>18</age>\"            >>" STRATEGY_FILE ";""echo \"\t\t\t<weight>61.38kg</weight>\" >>" STRATEGY_FILE ";""echo \"\t\t\t<married>false</married>\" >>" STRATEGY_FILE ";""echo \"\t\t</person>\"                  >>" STRATEGY_FILE ";""echo \"\t</strategy>\"                  >>" STRATEGY_FILE ";""echo \"</root>\"                        >>" STRATEGY_FILE );
#elif STRATEGY_FORMAT == FORMAT_JSON//.jsonsystem("echo \"{\"                                      >" STRATEGY_FILE ";""echo \"\t\\\"strategy\\\":{\"                  >>" STRATEGY_FILE ";""echo \"\t\t\\\"person\\\":{\"                  >>" STRATEGY_FILE ";""echo \"\t\t\t\\\"name\\\":\\\"john\\\",\"      >>" STRATEGY_FILE ";""echo \"\t\t\t\\\"age\\\":\\\"18\\\",\"         >>" STRATEGY_FILE ";""echo \"\t\t\t\\\"weight\\\":\\\"61.38kg\\\",\" >>" STRATEGY_FILE ";""echo \"\t\t\t\\\"married\\\":\\\"false\\\"\"   >>" STRATEGY_FILE ";""echo \"\t\t}\"                                 >>" STRATEGY_FILE ";""echo \"\t}\"                                   >>" STRATEGY_FILE ";""echo \"}\"                                     >>" STRATEGY_FILE);
#elif STRATEGY_FORMAT == FORMAT_INI//.inisystem("echo \"[strategy]\"           >" STRATEGY_FILE ";""echo \"id     =1234567890#\" >>" STRATEGY_FILE ";""echo \"name   =john#\"       >>" STRATEGY_FILE ";""echo \"age    =18#\"         >>" STRATEGY_FILE ";""echo \"weight =61.38kg#\"    >>" STRATEGY_FILE ";""echo \"married=false#\"      >>" STRATEGY_FILE);
#else//.txtsystem("touch " STRATEGY_FILE);
#endif
}/*main frame here*/
int main(){shadow_exception();prepare();init();while(!stop){sleep(2);read_use();}
#ifndef NDEBUG/*for view of debug*/printf("\nmain-thread waitting to collect resource ... \n");sleep(10);
#endifdestroy();return 0;
}

小结:

1)可以使用异步信号通知的方式,保持访问标志变量的一致性, 将更新线程与主线程停下来

2)通过最后一次修改时间与上一次做比对,来确定配置文件是否有更新,在同步更新时要注意清理上一次配置文件的内容 并 保持本次配置文件的完整性

3)读时共享,写时互斥(w-w,w-r), 区分writer与reader, 让需要配置的多线程最大程度并发,同时将需要同步竞争的数据拷贝来进一步提高reader并发量

4)更新配置文件一般是比较轻松的任务,可以最大限度让出CPU给系统其它任务使用

提示:实际开发当中配置文件会比较复杂,与业务逻辑强相关,常见的有XML, JSON, INI, TXT需要加载后解析到指定的内存结构,同步分给相应的任务使用

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/715842.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Mysql标量子查询

目录 子查询标量子查询数据准备 子查询 SQL语句中嵌套select语句&#xff0c;称为嵌套查询&#xff0c;又称子查询。 SELECT * FROM t1 WHERE column1 ( SELECT column1 FROM t2 ... );子查询外部的语句可以是insert / update / delete / select 的任何一个&…

git的安装、使用

文章目录 安装gitgit学习网站git初始配置具体配置信息 新建版本库&#xff08;仓库&#xff09;git的工作区域和文件状态工作区域文件状态git文件提交的基础指令 git基础指令1. 版本提交2. 分支创建3. 分支切换4. 分支合并(1) git merge(2) git rebase 5. 在git的提交树上移动(…

Ps:锐化工具

锐化工具 Sharpen Tool可用于增强图像局部区域的对比度&#xff0c;从而提高图像的清晰度和细节&#xff0c;特别适用于提升照片的边缘定义和纹理细节。 快捷键&#xff1a;无 ◆ ◆ ◆ 常用操作方法与技巧 1、如果直接在像素图像上使用锐化工具&#xff0c;可尝试使用“渐隐…

怎么优雅地访问ChatGPT

ChatGPT&#xff0c;这颗璀璨的智能结晶&#xff0c;在2022年岁末之际&#xff0c;由OpenAI实验室倾力铸就&#xff0c;犹如夜空中跃动的智慧星辰&#xff0c;点亮了人工智能领域的新纪元。犹如汪洋中的一座灯塔&#xff0c;ChatGPT以其独特的智慧光辉引人注目&#xff0c;然而…

Linux:kubernetes(k8s)node节点加入master主节点(3)

Linux&#xff1a;kubernetes&#xff08;k8s&#xff09;搭建mater节点&#xff08;kubeadm&#xff0c;kubectl&#xff0c;kubelet&#xff09;-CSDN博客https://blog.csdn.net/w14768855/article/details/136415575?spm1001.2014.3001.5502 我在上一章部署好了主节点&…

前端打包部署(黑马学习笔记)

我们的前端工程开发好了&#xff0c;但是我们需要发布&#xff0c;那么如何发布呢&#xff1f;主要分为2步&#xff1a; 1.前端工程打包 2.通过nginx服务器发布前端工程 前端工程打包 接下来我们先来对前端工程进行打包 我们直接通过VS Code的NPM脚本中提供的build按钮来完…

从下一代车规MCU厘清存储器的发展(2)

目录 1.概述 2.MCU大厂的选择 2.1 瑞萨自研STT-MRAM 2.2 ST专注PCM 2.3 英飞凌和台积电联手RRAM 2.4 NXP如何计划eNVM 3.小结 1.概述 上篇文章&#xff0c;我们简述了当前主流的存储器技术&#xff0c;现在我们来讲讲各大MCU大厂的技术选择 2.MCU大厂的选择 瑞萨日…

redis的RDB和AOF

Redis是一种高性能的键值对存储系统&#xff0c;它支持多种类型的数据结构&#xff0c;如字符串、列表、集合、哈希表、有序集合等。Redis提供了两种不同的持久化机制来确保数据的安全性&#xff1a;RDB&#xff08;Redis Database&#xff09;和AOF&#xff08;Append Only Fi…

Tomcat布署及优化二-----Mysql和虚拟机

1.Mysql搭Blog 1.1下载安装包 看一下tomcat状态 1.2放到指定目录 cp jpress-v3.2.1.war /usr/local/tomcat/webapps/ cd /usr/local/tomcat/webapps/ 1.3路径优化 ln -s jpress-v3.2.1 jpress 看jpress权限 1.4生成配置文件 cat >/etc/yum.repos.d/mysql.repo <<E…

掘根宝典之C语言指针详解

目录 什么是指针&#xff1f; 与指针相关的运算符 指针类型的意义 指针的大小 初始化 将指针直接指向一个已经存在的变量或内存地址&#xff1a; 使用malloc函数动态分配内存&#xff0c;并将指针指向新分配的内存&#xff1a; 使用calloc函数动态分配内存&#xff0c;并…

Javascript:常量与数据类型

一、前言 介绍完变量之后我们来对常量进行了解一番&#xff0c;关于常量我们需要知道些什么呢&#xff1f; 二、正文 1.常量的基本使用 使用const声明的变量称为常量&#xff0c;当某个变量的字面量无需改动的时候就能够用到常量。 //声明一个常量 const G 9.8 //输出这个常量…

您的计算机已被pings勒索病毒感染?恢复您的数据的方法在这里!

导言&#xff1a; 在数字时代&#xff0c;数据是企业和个人生活中不可或缺的一部分。然而&#xff0c;随着勒索病毒的不断进化和传播&#xff0c;我们的数据面临着前所未有的威胁。其中&#xff0c;.pings 勒索病毒是最新一轮威胁之一&#xff0c;它以其独特的加密算法和无情的…

leetcode-字符串中的单词数

434. 字符串中的单词数 题解&#xff1a; 这个问题可以通过遍历字符串&#xff0c;当遇到非空格字符时&#xff0c;判断其前一个字符是否为空格&#xff0c;如果是&#xff0c;则说明这是一个新的单词的开始&#xff0c;计数器加一。最后返回计数器的值即可。 class Solutio…

【Redis | 第一篇】快速了解Redis

文章目录 1.快速了解Redis1.1简介1.2与其他key-value存储的不同处1.3Redis安装——Windows环境1.3.1下载redis1.3.2启动redis1.3.3进入redis客户端1.3.4修改配置 1.4Redis安装——Linux环境1.4.1安装命令1.4.2启动redis1.4.3进入redis客户端 1.5配置修改1.6小结 1.快速了解Redi…

MyBatis 学习(七)之 缓存

目录 1 MyBatis 缓存介绍 2 一级缓存 3 二级缓存 3.1 二级缓存介绍 3.2 二级缓存配置 3.3 二级缓存测试 4 参考文档 1 MyBatis 缓存介绍 MyBatis 缓存是 MyBatis 中的一个重要特性&#xff0c;用于提高数据库查询的性能。MyBatis 提供了一级缓存和二级缓存两种类型的缓存…

Git与GitHub:解锁版本控制的魔法盒子

✨✨ 欢迎大家来访Srlua的博文&#xff08;づ&#xffe3;3&#xffe3;&#xff09;づ╭❤&#xff5e;✨✨ &#x1f31f;&#x1f31f; 欢迎各位亲爱的读者&#xff0c;感谢你们抽出宝贵的时间来阅读我的文章。 我是Srlua&#xff0c;在这里我会分享我的知识和经验。&#x…

cetos7 Docker 安装 gitlab

一、gitlab 简单介绍和安装要求 官方文档&#xff1a;https://docs.gitlab.cn/jh/install/docker.html 1.1、gitlab 介绍 gitLab 是一个用于代码仓库管理系统的开源项目&#xff0c;使用git作为代码管理工具&#xff0c;并在此基础上搭建起来的Web服务平台&#xff0c;通过该平…

(六)Dropout抑制过拟合与超参数的选择--九五小庞

过拟合 即模型在训练集上表现的很好&#xff0c;但是在测试集上效果却很差。也就是说&#xff0c;在已知的数据集合中非常好&#xff0c;再添加一些新数据进来效果就会差很多 欠拟合 即模型在训练集上表现的效果差&#xff0c;没有充分利用数据&#xff0c;预测准确率很低&a…

笨办法学 Python3 第五版(预览)(一)

原文&#xff1a;Learn Python the Hard Way, 5th Edition (Early Release) 译者&#xff1a;飞龙 协议&#xff1a;CC BY-NC-SA 4.0 模块 1&#xff1a;Python 入门 练习 0&#xff1a;准备工作 这个练习没有代码。这只是你完成的练习&#xff0c;让你的计算机运行 Python。…

Unity 游戏设计模式:单例模式

本文由 简悦 SimpRead 转码&#xff0c; 原文地址 mp.weixin.qq.com 单例模式 在 C# 游戏设计中&#xff0c;单例模式是一种常见的设计模式&#xff0c;它的主要目的是确保一个类只有一个实例&#xff0c;并提供一个全局访问点。单例模式在游戏开发中具有以下几个作用&#xf…