Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 542
vitaut Avatar asked Dec 27 '12 23:12

vitaut


People also ask

Is Gmock thread safe?

Since the GoogleMock documentation says that it is, or should be, thread safe on systems with pthreads, it should be thread safe on Linux. I did have to add -pthread to the linker command line to build the executable. That means that GoogleMock or GoogleTest does use pthreads.

How do I run a Gtest disabled test?

If you know a test will fail before running it, then you can disable it temporarily by prepending DISABLED_ to the test name.

Does Google Test run tests in parallel?

gtest-parallel is a script that executes Google Test binaries in parallel, providing good speedup for single-threaded tests (on multi-core machines) and tests that do not run at 100% CPU (on single- or multi-core machines).

What is Expect_eq?

EXPECT_EQ and ASSERT_EQ are also macros—in the former case test execution continues even if there is a failure while in the latter case test execution aborts. Clearly, if the square root of 0 is anything but 0, there isn't much left to test anyway.


1 Answers

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);
}
like image 183
vitaut Avatar answered Oct 08 '22 02:10

vitaut