问题
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