我正在尝试编写简单的调试宏,该宏将与运行它的多个线程一起使用。我显然错过了一些东西,因为 std::cout 输出不同步。非常感谢任何帮助。
//=======Debugger========//
#ifndef _DEBUGGER_H_
#define _DEBUGGER_H_
#include <iostream>
#include <thread>
#include <mutex>
/*
* Debugger. All messages are directed to std::cout
*/
#ifndef WITH_NOCOLOR
#define COLOR_GREEN "\e[0;32m"
#define COLOR_RED "\e[1;91m"
#define COLOR_CYAN "\e[1;36m"
#define COLOR_YELLOW "\e[1;33m"
#define COLOR_ORANGE "\e[0;33m"
#define RESET_COLOR "\e[m"
#else
#define COLOR_GREEN ""
#define COLOR_RED ""
#define COLOR_CYAN ""
#define COLOR_YELLOW ""
#define COLOR_ORANGE ""
#define RESET_COLOR ""
#endif //WITH_NOCOLOR
#define THREAD_ID "[thread: " << std::this_thread::get_id() << "] "
#define THREAD_SYNC_START { std::lock_guard< std::mutex > lock( sync_mutex );
#define THREAD_SYNC_STOP }
static std::mutex sync_mutex;
#define DEBUG "[Debug]: "
#define ERROR "[Error]: "
#define INFO "[Info ]: "
#define WARNING "[Warn ]: "
#define Debug(x) do { THREAD_SYNC_START \
std::cout << COLOR_CYAN << DEBUG << RESET_COLOR << THREAD_ID << x << std::endl; \
THREAD_SYNC_STOP \
}while(0)
#define Err(x) do { THREAD_SYNC_START \
std::cout << COLOR_RED << ERROR << COLOR_ORANGE << THREAD_ID << x << RESET_COLOR << std::endl; \
THREAD_SYNC_STOP \
}while(0)
#define Info(x) do { THREAD_SYNC_START \
std::cout << INFO << THREAD_ID << x <<std::endl; \
THREAD_SYNC_STOP \
}while(0)
#define Warn(x) do { THREAD_SYNC_START \
std::cout << COLOR_YELLOW << WARNING << RESET_COLOR << THREAD_ID << x << std::endl; \
THREAD_SYNC_STOP \
}while(0);
#endif //_DEBUGGER_H_
输出:
[Debug]: [thread: [Debug]: [thread: 1074275136] Starting Log..1099953248] init start
最佳答案
您的sync_mutex
是一个static
命名空间范围变量,这意味着它具有内部链接 - 每个翻译单元(.cpp
文件)其中包括 header 将有其自己的互斥体拷贝。因此,来自不同翻译单元的访问不同步。
您需要确保整个程序只有一个 sync_mutex
对象。最明显的方法是将互斥锁转换为 extern
变量而不是 static
变量,然后在一个源文件中定义它。
或者,如果您想仅保留 header ,则可以将其作为内联函数内的静态局部变量:
#define THREAD_SYNC_START { std::lock_guard< std::mutex > lock( sync_mutex() );
inline std::mutex& sync_mutex()
{
static std::mutex m;
return m;
}
关于C++ 多线程调试宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31073364/