Command-line options to force googletest to run in single thread

ⅰ亾dé卋堺 提交于 2021-02-07 06:45:06

问题


I have a suite of unit tests that is managed by googletest. These tests are run in multiple threads by default, even when I use --gtest_filter=foo.test so that it only runs a single test. This is causing ambiguity about the cause of a bug I'm trying to hammer out.

How can multithreaded testing be turned off in googletest?


回答1:


There's no commandline switch for single/multi-threading. libgtest is built either single-threading or multi-threading.

To make it single-threading, build gtest with ./configure --with-pthreads=no, then link your unit test app without -pthread

If you only want single threading sometimes, then make a no-pthreads build of libgtest, call it something else, and link it when you want.




回答2:


If you are building googletest with cmake, you can use the cmake option gtest_disable_pthreads to control support for threading. For example:

$ mkdir build && cd build
$ cmake .. -Dgtest_disable_pthreads=ON

The resulting output should not show:

-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - found
-- Found Threads: TRUE  

Then you can run make as usual.




回答3:


Another option short of rebuilding with multi-threading disabled is to simply create a test fixture for tests that cannot run concurrently. Then in the SetUp() and TearDown() methods, lock and unlock a mutex respectivey.

Be sure to use a mutex that exists outside of the test fixture, as the fixture is created and torn down for every test.

std::mutex g_singleThread;

class SingleThreadedTests
{
protected:
   virtual void SetUp() override
   {
      g_singleThread.lock();
   }

   virtual void TearDown() override
   {
      g_singleThread.unlock();
   }
};

TEST_F(SingleThreadedTests, MyTest)
{
   // ...
}


来源:https://stackoverflow.com/questions/29335446/command-line-options-to-force-googletest-to-run-in-single-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!