简体   繁体   English

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

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

When running the death tests written using Google Test framework the following warning is produced for each of the tests: 运行使用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.

Is there a way to make Google Test detect the number of threads on Linux? 有没有办法让Google Test检测Linux上的线程数?

I've looked at the source code and it turned out that detection of the number of threads is implemented only for MacOS X and QNX, but not on Linux or other platforms. 我查看了源代码,结果发现线程数的检测仅针对MacOS X和QNX实现,但不适用于Linux或其他平台。 So I implemented missing functionality myself by counting the number of entries in /proc/self/task . 所以我通过计算/proc/self/task的条目数来自己实现缺少的功能。 Since it might be useful for others I'm posting it here (I've also sent it to the Google Test group ): 因为它可能对其他人有用,我在这里发布它(我也将它发送给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;
}

As of 25 August 2015, Google Test implements GetThreadCount on Linux : 截至2015年8月25日,Google Test 在Linux上实施GetThreadCount

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

If you don't care much about the test execution time, a convenient alternative is to use: 如果您不太关心测试执行时间,一个方便的替代方法是使用:

::testing::FLAGS_gtest_death_test_style = "threadsafe";

More details here . 更多细节在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM