我正在尝试使用 google test/mock 测试阻塞与异步。
不幸的是,我无法想出某种测试来确保异步在第一种情况下发生,而在第二种情况下发生阻塞。
有没有办法确认 std::future 的行为是否正常?
代码
#include <gtest/gtest.h>
#include <future>
static unsigned a_slow_calc()
{
sleep( 1 );
return 1u;
}
TEST( Test_future, Ensure_async )
{
// 1. immediately returns
std::future<unsigned> answer = std::async( a_slow_calc );
// 2. std::future::get BLOCKS until the result is ready
EXPECT_EQ( 1u, answer.get() );
}
最佳答案
您应该使用 std::launch::async
启动策略。您的第一个函数调用不保证立即返回你在上面写的评论。
默认策略是在这个线程或另一个线程上完成工作。您当前的代码可能会在您的机器上通过测试,但在客户端的机器上可能会失败...
如果您使用 std::launch::async
策略,那么您的测试基本上是在测试 C++11 标准。换句话说,你想测的,标准已经保证了。
关于c++ - 如何测试阻塞与异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14272184/