C++ GoogleMock在Linux上不是线程安全的吗?

C++ GoogleMock在Linux上不是线程安全的吗?,c++,linux,multithreading,visual-studio,googlemock,C++,Linux,Multithreading,Visual Studio,Googlemock,我开始在Windows上测试GoogleMock(1.8.0版)。我想展示一个例子,说明它不是线程安全的。在成功地证明了这一点之后,我想证明同样的测试在Linux上运行良好。然而,这失败了。这不符合我的期望。 因为GoogleMock文档说它在使用pthreads的系统上是线程安全的,或者应该是线程安全的,所以它在Linux上应该是线程安全的。我确实需要将-pthread添加到链接器命令行以构建可执行文件。这意味着GoogleMock或GoogleTest确实使用pthreads 这是我用于测试

我开始在Windows上测试GoogleMock(1.8.0版)。我想展示一个例子,说明它不是线程安全的。在成功地证明了这一点之后,我想证明同样的测试在Linux上运行良好。然而,这失败了。这不符合我的期望。 因为GoogleMock文档说它在使用pthreads的系统上是线程安全的,或者应该是线程安全的,所以它在Linux上应该是线程安全的。我确实需要将
-pthread
添加到链接器命令行以构建可执行文件。这意味着GoogleMock或GoogleTest确实使用pthreads

这是我用于测试的代码:

#include <thread>
#include <vector>

#include "gmock/gmock.h"

class Dummy
{
public:
    virtual void SomeMethod(int) {}
};

class DummyMock : public Dummy
{
public:
    MOCK_METHOD1(SomeMethod, void(int));
};

using ::testing::Exactly;

constexpr static int nrCallsPerThread = 100 * 1000;
constexpr static int nrThreads = 10;

TEST(SomeTest, Test100)
{
    DummyMock dummy;

    std::vector<std::thread> threads;
    for (int i = 0; i < nrThreads; i++)
    {
        EXPECT_CALL(dummy, SomeMethod(i)).Times(Exactly(nrCallsPerThread));
        threads.emplace_back([&dummy, i]
        {
            for (int j = 0; j < nrCallsPerThread; j++)
            {
                dummy.SomeMethod(i);
            }
        });
    }

    for (auto& t: threads)
    {
        t.join();
    }
}

int main(int argc, char** argv)
{
    testing::InitGoogleMock(&argc, argv);
    return RUN_ALL_TESTS();
}
因为它应该是线程安全的,所以我怀疑我做错了什么。但我不明白。 还是我在GoogleTest或GoogleMock中遇到了错误?

来自《精细手册》:

重要提示:Google Mock要求在调用模拟函数之前设置期望值,否则行为是未定义的。特别是,您不能将EXPECT_CALL()和对模拟函数的调用交织在一起

您的原始代码在我的系统(cygwin)上间歇性失败,出现错误22,或者有时没有任何消息/错误代码。此修改工作完美无瑕:

for (int i = 0; i < nrThreads; i++)
{
    EXPECT_CALL(dummy, SomeMethod(i)).Times(Exactly(nrCallsPerThread));
}

std::vector<std::thread> threads;
for (int i = 0; i < nrThreads; i++)
{
    threads.emplace_back([&dummy, i] ...
for(int i=0;i
您还必须将-pthread添加到编译器命令行。@n.m.为什么?编译器,或者更具体的预处理器,在googlemock和googletest头中包含基于条件编译的pthread头。因为这是。谢谢您修复了它。我试图实现的是创建一些w GoogleMock在Windows上不是线程安全的,但在Linux上是线程安全的。你@n.m.知道一个例子吗?食谱上说:
使用GoogleMock和线程重要注意:我们在这个食谱中描述的只有在GoogleMock是线程安全的平台上才是正确的。目前,这些平台是唯一支持pthreads库的平台(这包括Linux和Mac)。为了在其他平台上实现线程安全,我们只需要在“gtest/internal/gtest port.h”中实现一些同步操作即可。
作为对我个人评论的回应。这就是谷歌模拟烹饪书目前(仍然)的内容但是,当我查看gmock也使用的
gtest port.cc
的内部结构时,我发现
类互斥体
是使用
::XxxCriticalSection
实现的。因此,这本烹饪书在这个主题上可能已经过时,并且仍然参考了对1.7.0版和更早版本有效的内容。
for (int i = 0; i < nrThreads; i++)
{
    EXPECT_CALL(dummy, SomeMethod(i)).Times(Exactly(nrCallsPerThread));
}

std::vector<std::thread> threads;
for (int i = 0; i < nrThreads; i++)
{
    threads.emplace_back([&dummy, i] ...