C ++多线程调试宏

时间:2015-06-26 12:36:58

标签: c++ multithreading macros

我正在尝试编写简单的调试宏,它将与运行它的多个线程一起使用。我显然必须遗漏一些东西,因为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

1 个答案:

答案 0 :(得分:3)

sync_mutex是一个static命名空间范围变量,这意味着它有内部链接 - 包含标题的每个翻译单元(.cpp文件)都有自己的副本互斥体。因此,来自不同翻译单元的访问不同步。

您需要确保整个程序只有一个sync_mutex对象。最明显的方法是将互斥锁转换为extern变量而不是static变量,然后在一个源文件中定义它。

或者,如果您想保留仅标题,则可以将其作为内联函数中的静态局部变量:

#define THREAD_SYNC_START   { std::lock_guard< std::mutex > lock( sync_mutex() );

inline std::mutex& sync_mutex()
{
  static std::mutex m;
  return m;
}