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

vit*_*aut 12 c++ linux multithreading thread-safety googletest

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

[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.
Run Code Online (Sandbox Code Playgroud)

有没有办法让Google Test检测Linux上的线程数?

vit*_*aut 11

我查看了源代码,结果发现线程数的检测仅针对MacOS X和QNX实现,但不适用于Linux或其他平台.所以我通过计算输入的条目数来自己实现缺失的功能/proc/self/task.因为它可能对其他人有用,我在这里发布它(我也将它发送给Google Test小组):

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;
}
Run Code Online (Sandbox Code Playgroud)

截至2015年8月25日,Google Test 在Linux上实施GetThreadCount:

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


Pau*_*scu 5

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

::testing::FLAGS_gtest_death_test_style = "threadsafe";
Run Code Online (Sandbox Code Playgroud)

更多细节在这里.