如何让Google Test检测Linux上的线程数

How to make Google Test detect the number of threads on Linux?

本文关键字:线程 Linux 检测 Google Test      更新时间:2023-10-16

运行使用Google测试框架编写的死亡测试时,会为每个测试生成以下警告:

[WARNING] .../gtest-death-test.cc:789:: Death tests use fork(), which is unsafe
particularly in a threaded context. For this test, Google Test couldn't detect
the number of threads.

是否有一种方法可以使谷歌测试检测Linux上的线程数?

我查看了源代码,结果发现线程数检测只在MacOS X和QNX上实现,而在Linux或其他平台上没有。所以我通过计算/proc/self/task中的条目数来实现缺失的功能。因为它可能对其他人有用,我把它贴在这里(我也把它发送到谷歌测试组):

size_t GetThreadCount() {
  size_t thread_count = 0;
  if (DIR *dir = opendir("/proc/self/task")) {
    while (dirent *entry = readdir(dir)) {
      if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0)
        ++thread_count;
    }
    closedir(dir);
  }
  return thread_count;
}

截至2015年8月25日,谷歌测试在Linux上实现GetThreadCount:

size_t GetThreadCount() {
  const string filename =
      (Message() << "/proc/" << getpid() << "/stat").GetString();
  return ReadProcFileField<int>(filename, 19);
}

如果您不太关心测试执行时间,一个方便的替代方法是使用:

::testing::FLAGS_gtest_death_test_style = "threadsafe";