如何测试阻塞与异步?

时间:2013-01-11 05:22:47

标签: c++ testing stl c++11 future

我正在尝试使用google test / mock测试阻止与异步。

不幸的是,我无法进行某种测试以确保在第一种情况下发生异步并在第二种情况下发生阻塞。

有没有办法确认std :: future的行为方式应该如何?

CODE

#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() );
}

2 个答案:

答案 0 :(得分:3)

您应该使用 std::launch::async 启动政策。您的第一个函数调用不能保证立即返回,而不是您在其上面写的注释。

默认策略是对此或另一个线程执行操作。您当前的代码可能会通过您计算机上的 ,但可能会在客户端的计算机上失败...

如果您使用std::launch::async策略,那么您的测试基本上是测试C ++ 11标准。换句话说,您希望测试的内容已经由标准保证。

答案 1 :(得分:1)

您可以在future上使用wait_for,超时为零(或非常小),并查看其是否返回值future_status::timeout

相关问题