如何将日志异步工作器的实现改写为一个长尾词的?
- 内容介绍
- 文章标签
- 相关推荐
本文共计443个文字,预计阅读时间需要2分钟。
实现一个日记异步工作器,用于异步记录日记内容。该工作器能够将用户输入的日记内容异步写入文件,而不会阻塞主程序流程。
pythonimport asyncio
class DiaryAsyncWorker: def __init__(self, file_path): self.file_path=file_path
async def write_diary(self, content): async with aiofiles.open(self.file_path, 'a') as file: await file.write(content + '\n')
async def main(): worker=DiaryAsyncWorker('diary.txt') diary_content=今天天气不错,心情很好。 await worker.write_diary(diary_content)
运行异步主函数asyncio.run(main())
日志异步工作器的实现
/*实现异步工作器*/
#ifndef __M_LOOPER_H__
#define __M_LOOPER_H__
#include <mutex>
#include <thread>
#include <condition_variable> //条件变量
#include "buffer.hpp"
#include <functional>
#include <memory>
namespace nmzlog
{
// 异步工作器
class AsyncLooper
{
// 定义一个function类型
using Functor = std::function<void(Buffer &)>; // 定义一个函数指针的类型
public:
// 构造函数
AsyncLooper() {}
using ptr = std::shared_ptr<AsyncLooper>; // 定义一个只能指针类型
void stop();
// 提供数据
void push(const char *data, size_t len); // 不断新增,扩容的时候就不断添加到内存中,如果是固定大小就会阻塞
private:
// 回调函数
Functor _callBack;//具体对缓冲区数据进行处理的回调函数,由异步工作器使用者来传入
private:
// 线程的入口函数
void threadEntry();
private:
bool _stop; // 工作器停止标志,是否停止异步工作器,是true,否false
Buffer _pro_buf; // 生产缓冲区
Buffer _con_buf; // 消费缓冲区
std::mutex _mutex; // 互斥锁保证安全
// 条件变量头文件condition_variable
// 两个条件变量,会提供两个pcb的等待队列
std::condition_variable _cond_pro; // 生产者的等待队列的条件变量
std::condition_variable _cond_con; //
std::thread _thread; // 异步工作器对应的工作线程
};
}
#endif
本文共计443个文字,预计阅读时间需要2分钟。
实现一个日记异步工作器,用于异步记录日记内容。该工作器能够将用户输入的日记内容异步写入文件,而不会阻塞主程序流程。
pythonimport asyncio
class DiaryAsyncWorker: def __init__(self, file_path): self.file_path=file_path
async def write_diary(self, content): async with aiofiles.open(self.file_path, 'a') as file: await file.write(content + '\n')
async def main(): worker=DiaryAsyncWorker('diary.txt') diary_content=今天天气不错,心情很好。 await worker.write_diary(diary_content)
运行异步主函数asyncio.run(main())
日志异步工作器的实现
/*实现异步工作器*/
#ifndef __M_LOOPER_H__
#define __M_LOOPER_H__
#include <mutex>
#include <thread>
#include <condition_variable> //条件变量
#include "buffer.hpp"
#include <functional>
#include <memory>
namespace nmzlog
{
// 异步工作器
class AsyncLooper
{
// 定义一个function类型
using Functor = std::function<void(Buffer &)>; // 定义一个函数指针的类型
public:
// 构造函数
AsyncLooper() {}
using ptr = std::shared_ptr<AsyncLooper>; // 定义一个只能指针类型
void stop();
// 提供数据
void push(const char *data, size_t len); // 不断新增,扩容的时候就不断添加到内存中,如果是固定大小就会阻塞
private:
// 回调函数
Functor _callBack;//具体对缓冲区数据进行处理的回调函数,由异步工作器使用者来传入
private:
// 线程的入口函数
void threadEntry();
private:
bool _stop; // 工作器停止标志,是否停止异步工作器,是true,否false
Buffer _pro_buf; // 生产缓冲区
Buffer _con_buf; // 消费缓冲区
std::mutex _mutex; // 互斥锁保证安全
// 条件变量头文件condition_variable
// 两个条件变量,会提供两个pcb的等待队列
std::condition_variable _cond_pro; // 生产者的等待队列的条件变量
std::condition_variable _cond_con; //
std::thread _thread; // 异步工作器对应的工作线程
};
}
#endif

