/**************************************************************
技术博客 
技术交流群
群号码:324164944

欢迎c c++ windows驱动爱好者 服务器程序员沟通交流

**************************************************************/

使用c++11 写个日志类

主要练习 线程 互斥量的使用

代码如下:

#include "stdafx.h"
#include "Logger.h"
#include <fstream>
#include <iostream> Logger::Logger(const string& filepath):
filePath_(filepath)
{ } Logger::~Logger()
{ thread_.join();
} bool Logger::init()
{
bool bRet = false;
thread_ = thread{ &Logger::LogThreadFunc, this };
unique_lock<mutex> lock(mutexStarted_);
condVarStarted_.wait(lock); bRet = true;
return bRet;
} void Logger::Log(const std::string& content)
{
unique_lock<mutex> lock(mutex_);
queue_.push(content); } void Logger::LogThreadFunc()
{
ofstream ofs(filePath_);
if (ofs.fail()) {
cerr << "Failed to open logfile." << endl;
return;
} cout << "enter thread" << endl;
unique_lock<mutex> lock(mutex_,std::defer_lock);
condVarStarted_.notify_all(); while (true){
lock.lock();
condVar_.wait(lock);
lock.unlock(); while (true){
lock.lock();
if (queue_.empty()) {
lock.unlock();
break;
}
else {
ofs << queue_.front() << endl;
queue_.pop();
}
lock.unlock();
}
if (bExit_){
break;
}
} }

  

#ifndef LOGGER_H__
#define LOGGER_H__ #include <queue>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable> #define DEFAULT_FILE_NAME "test.dat" using namespace std; class Logger{
public:
Logger(const string& filepath = DEFAULT_FILE_NAME);
virtual ~Logger();
bool init(); void Log(const std::string& content);
void LogThreadFunc();
void SetExitFlag(){
bExit_ = true;
condVar_.notify_all();
};
private:
string filePath_;
bool bExit_;
std::condition_variable condVar_;
std::condition_variable condVarStarted_;
std::thread thread_;
std::mutex mutex_;
std::mutex mutexStarted_;
std::queue<std::string> queue_;
Logger& operator=(const Logger& rhs);
}; #endif

  测试代码如下:

// 1111.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include "Logger.h"
#include <iostream>
#include <sstream>
#include <thread>
#include <vector> void logSomeMessages(int id, Logger& logger)
{
for (int i = 0; i < 100; ++i) {
stringstream ss;
ss << "Log test " << i << " from thread " << id;
logger.Log(ss.str());
}
} int _tmain(int argc, _TCHAR* argv[])
{
Logger log;
log.init(); vector<thread> threads;
// Create a few threads all working with the same Logger instance.
for (int i = 0; i < 100; ++i) {
threads.push_back(thread{ logSomeMessages, i, ref(log) });
} for (auto& t : threads) {
t.join();
} log.SetExitFlag();
return 0;
}

  

c++11日志练习的更多相关文章

  1. [译]Stairway to Integration Services Level 11 - 日志配置

    介绍 在前一个章节我们讨论了事先行为,分享了如何操作默认的行为和时间冒泡,并且介绍了父子模型. 本文中,我们会配置SSIS日志. 进行简单及高级日志配置,存储,和检索的实验.并且生成自定义日志信息. ...

  2. Go语言学习之11 日志收集系统kafka库实战

    本节主要内容: 1. 日志收集系统设计2. 日志客户端开发 1. 项目背景    a. 每个系统都有日志,当系统出现问题时,需要通过日志解决问题    b. 当系统机器比较少时,登陆到服务器上查看即可 ...

  3. ogre3D学习基础11 -- 日志文件的使用与异常处理

    用文件来记录 Ogre 系统初始化.运行.结束以及调试信息.使用日志便于我们调试程序.Ogre 日志系统由两个类组成:Log 类与 LogManager. 1.Log类 Log 类的一个对象对应于一个 ...

  4. ELK+Filebeat+Kafka+ZooKeeper 构建海量日志分析平台(elk5.2+filebeat2.11)

    ELK+Filebeat+Kafka+ZooKeeper 构建海量日志分析平台 参考:http://www.tuicool.com/articles/R77fieA 我在做ELK日志平台开始之初选择为 ...

  5. atitit. 日志系统的原则and设计and最佳实践(1)-----原理理论总结.

    atitit. 日志系统的原则and设计and最佳实践总结. 1. 日志系统是一种不可或缺的单元测试,跟踪调试工具 1 2. 日志系统框架通常应当包括如下基本特性 1 1. 所输出的日志拥有自己的分类 ...

  6. Centos6.5使用ELK(Elasticsearch + Logstash + Kibana) 搭建日志集中分析平台实践

    Centos6.5安装Logstash ELK stack 日志管理系统 概述:   日志主要包括系统日志.应用程序日志和安全日志.系统运维和开发人员可以通过日志了解服务器软硬件信息.检查配置过程中的 ...

  7. Oracle 联机重做日志文件(ONLINE LOG FILE)

    --========================================= -- Oracle 联机重做日志文件(ONLINE LOG FILE) --================== ...

  8. Spring aop+自定义注解统一记录用户行为日志

    写在前面 本文不涉及过多的Spring aop基本概念以及基本用法介绍,以实际场景使用为主. 场景 我们通常有这样一个需求:打印后台接口请求的具体参数,打印接口请求的最终响应结果,以及记录哪个用户在什 ...

  9. Natasha V1.3.6.0 的升级日志

    开源库满足于个人,而完善于大众. Natasha 自稳定版发布之后,众多老铁参与增强改进,感谢如下老铁的反馈: 1. 异常搜集 在 wenjq0911 建议下,添加了异常捕获,现 Natasha 的编 ...

随机推荐

  1. HTML5 Canvas ( 径向渐变, 升级版的星空 ) fillStyle, createRadialGradient

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  2. Eclipse 中yml自动提示功能相关设置

    转自:https://blog.csdn.net/lililuni/article/details/82849376

  3. 使用示例带你提前了解 Java 9 中的新特性

    使用示例带你提前了解 Java 9 中的新特性 转载来源:https://juejin.im/post/58c5e402128fe100603cc194 英文出处:https://www.journa ...

  4. 机器学习入门-数据下采样 np.random_choice

    1. np.random_choice(array, len)  进行随机的数据选择,array表示抽取的对象,len表示抽取样本的个数 数据的下采样是对多的数据进行np.random.choice ...

  5. jsfl 巧用获取jsfl绝对路径,导入配置文件,注意配置文件无法改变舞台宽高

    //获取jsfl下的AS3.xml配置文件的路径 var jsflURL_arr=fl.scriptURI.split("/"); jsflURL_arr.splice(jsflU ...

  6. BLOB 操作

    对于数据库是BLOB类型存储数据. BLOB数据插入: Oracle提供的标准方式: 先插入一个空BLOB对象,然后Update这个空对象. 首先使用empty_blob()函数插入一个空BLOB对象 ...

  7. Safari-IoS调试

    打开Safari浏览器,进入扩展功能,打开开发功能. 手机模拟器在设置中选择 javascript调试允许. 在模拟器中的页面,在Safari浏览器-开发模式-Serinator中选择打开的页面,即可 ...

  8. python 之九九乘法表

    for i in range(1,10): for j in range(1,i+1): print(f"{j}*{i}={i*j}",end='\t') print() 运行结果 ...

  9. spring cloud DashBoard

    1 依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring ...

  10. Mybatis知识(2)

    1.#{}和${}的区别是什么? 注:这道题是面试官面试我同事的. 答:${}是Properties文件中的变量占位符,它可以用于标签属性值和sql内部,属于静态文本替换,比如${driver}会被静 ...