13

When running the death tests written using Google Test framework the following warning is produced for each of the tests:

[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?

vitaut
  • 49,672
  • 25
  • 199
  • 336

2 Answers2

11

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. So I implemented missing functionality myself by counting the number of entries in /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):

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:

size_t GetThreadCount() {
  const string filename =
      (Message() << "/proc/" << getpid() << "/stat").GetString();
  return ReadProcFileField<int>(filename, 19);
}
vitaut
  • 49,672
  • 25
  • 199
  • 336
  • Slight optimisation, since all the entries would be numbers, you could just do `if (entry->d_name[0] != '.') ... ` instead of your two calls to strcmp... I'm sure it doesn't matter really... – Mats Petersson Dec 28 '12 at 01:03
  • 1
    I do like your solution, by the way. – Mats Petersson Dec 28 '12 at 01:05
  • @MatsPetersson: Thanks. You are right about the performance, but it is only for death tests which are slowish anyway. – vitaut Dec 28 '12 at 01:09
  • 1
    Here's a link to the gtest issue and patch (tested on Ubuntu 14.04 with gcc 4.9): https://code.google.com/p/googletest/issues/detail?id=464&q=couldn%27t%20detect&colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary – Kurt Aug 08 '14 at 16:15
6

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.

psur
  • 4,400
  • 26
  • 36
Paul Baltescu
  • 2,095
  • 4
  • 25
  • 30
  • 1
    I do care about test execution time, but thanks for the answer. Didn't know about this option. – vitaut Feb 18 '15 at 14:02
  • It can be also passed as command line argument: `--gtest_death_test_style=threadsafe` – psur Jan 14 '16 at 08:06