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

How to make Google Test detect the number of threads on 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. 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);}


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.