我正在尝试创建一个日志记录类,其中写入日志的调用是静态的。现在,由于性能要求,我想在单独的线程中执行实际的日志记录。由于写入日志的函数是静态的,我认为线程也需要是静态的,这也与另一个执行实际写入日志的静态成员函数相关联。我尝试对其进行编码,但不知何故它在静态线程的初始化过程中挂起。复制该行为的代码示例如下:
“记录器.h”
#ifndef LOGGER_H
#define LOGGER_H
#include <condition_variable>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <vector>
#define LIBRARY_EXPORTS
#ifdef LIBRARY_EXPORTS // inside DLL
#define LIBRARY_API __declspec(dllexport)
#else // outside DLL
#define LIBRARY_API __declspec(dllimport)
#endif
using namespace std;
namespace Company { namespace Logging {
class LIBRARY_API Logger
{
public:
~Logger();
void static Write(string message, vector<string> categories = vector<string>());
private:
Logger();
Logger(Logger const&) {}
void operator=(Logger const&) {}
static thread processLogEntriesThread;
static void ProcessLogEntries();
};
}}
#endif
“记录器.cpp”
#include "Logger.h"
#include <iostream>
using namespace std;
namespace Company { namespace Logging {
thread Logger::processLogEntriesThread = thread(&Logger::ProcessLogEntries);
Logger::Logger()
{
}
Logger::~Logger()
{
Logger::processLogEntriesThread.join();
}
void Logger::Write(string message, vector<string> categories)
{
cout << message << endl;
}
void Logger::ProcessLogEntries()
{
}
}}
我发现的一个奇怪行为是,仅当类打包在 DLL 中时才会发生挂起部分。如果我将类文件直接使用到控制台 EXE 项目中,它似乎可以工作。
所以基本上我的问题是悬挂部分,如果我做对了。
提前致谢...