예제 #1
0
void GoApp::check_for_computed_move()
{
	//return;

	if (game_status != COMPUTER_THINKING) {
		return;
	}

	auto status = computed_move.wait_for(std::chrono::seconds(0));
	if (status == std::future_status::ready) {
		try {
			auto move = computed_move.get();
			state.do_move(move);

			// Are there any more moves possible?
			if (state.get_moves().empty()) {
				game_status = GAME_OVER;
			}
			else {
				next_player();
			}

		} catch (std::exception& error) {
			game_status = GAME_ERROR;
			error_string = error.what();
		}
	}
}
예제 #2
0
int factorial1(std::future<int>& f)
{
    int n = f.get();
    int result = 1;
    for (int i = 1; i <= n; ++i)
        result *= i;

    return result;
}
예제 #3
0
    /**
     * Close the task. This will raise in this thread any exception the
     * task generated in the other thread. Calling this function is
     * optional, because the destructor will also call this function.
     * But because it can throw an exception, it is better to call it
     * explicitly.
     */
    void close() {
        // If an exception happened in the task, re-throw
        // it in this thread. This will block if the task
        // isn't finished.
        if (m_future.valid()) {
            m_future.get();
        }

        // Make sure task is done.
        if (m_thread.joinable()) {
            m_thread.join();
        }
    }
void handleFuture( std::future< _2Real::BlockResult > &obj, std::string const& info = "" )
{
	obj.wait();
	_2Real::BlockResult val = obj.get();
	switch ( val )
	{
	case _2Real::BlockResult::CARRIED_OUT:
		std::cout << "---- " << info << " was carried out" << std::endl;
		break;
	case _2Real::BlockResult::IGNORED:
		std::cout << "---- " << info << " was ignored" << std::endl;
		break;
	}
}
예제 #5
0
파일: main.cpp 프로젝트: CCJY/coliru
 std::pair<long double, int> getResult(
     std::chrono::system_clock::time_point deadline, int maxPrecision)
 {
     long double result = 1;
     int precision = 1;
     if (std::chrono::system_clock::now() < deadline) {        
         while (precision < maxPrecision) {
             const int nextPrecision = std::min(maxPrecision, precision * 2);
             future = std::async(std::launch::async, compute, nextPrecision);
             if (future.wait_until(deadline) == std::future_status::timeout)
                 break;
             result = future.get();
             precision = nextPrecision;
         }
     }
     return { result, precision };
 }
예제 #6
0
            /**
             * Get the header data from the file.
             *
             * @returns Header.
             * @throws Some form of osmium::io_error if there is an error.
             */
            osmium::io::Header header() {
                if (m_status == status::error) {
                    throw io_error("Can not get header from reader when in status 'error'");
                }

                try {
                    if (m_header_future.valid()) {
                        m_header = m_header_future.get();
                        if (m_read_which_entities == osmium::osm_entity_bits::nothing) {
                            m_status = status::eof;
                        }
                    }
                } catch (...) {
                    close();
                    m_status = status::error;
                    throw;
                }
                return m_header;
            }
예제 #7
0
//========================================================================
void CSirServer::NotifyResult(CLIENT* client, std::future<SCRESULT>& result)
{
	SCRESULT rc = result.get();
	stringstream ss;

	switch (rc)
	{
		case SCR_SUCCESS:
			ss << "OK";
		break;

		case SCR_TIMEOUT:
			ss << "TIMEOUT";
		break;

		default:
			ss << "ERROR";
		break;
	}
	ss << std::endl;

	Notify(client, ss.str());
}
예제 #8
0
    void on_update(const UpdateEvent & e) override
    {
        // Around 60 fps
        if (fixedTimer.milliseconds().count() >= 16 && turret.fired)
        {
            float timestep_ms = fixedTimer.milliseconds().count() / 1000.f;
            turret.projectile.fixed_update(timestep_ms);
            std::cout << timestep_ms << std::endl;
            //std::cout << turret.projectile.p.position << std::endl;
            fixedTimer.reset();
        }

        cameraController.update(e.timestep_ms);
        time += e.timestep_ms;
        shaderMonitor.handle_recompile();

        // If a new mesh is ready, retrieve it
        if (pointerFuture.valid())
        {
            auto status = pointerFuture.wait_for(std::chrono::seconds(0));
            if (status != std::future_status::timeout)
            {
                auto m = pointerFuture.get();
                supershape = m;
                supershape.pose.position = {0, 2, -2};
                pointerFuture = {};
            }
        }

        // If we don't currently have a background task, begin working on the next mesh
        if (!pointerFuture.valid() && regeneratePointer)
        {
            pointerFuture = std::async([]() {
                return make_supershape_3d(16, ssM, ssN1, ssN2, ssN3);
            });
        }
    }
TEST_F(DBusConnectionTest, LibdbusConnectionsMayCommitSuicide) {
    const ::DBusBusType libdbusType = ::DBusBusType::DBUS_BUS_SESSION;
    ::DBusError libdbusError;
    dbus_error_init(&libdbusError);
    ::DBusConnection* libdbusConnection = dbus_bus_get_private(libdbusType, &libdbusError);

    assert(libdbusConnection);
    dbus_connection_set_exit_on_disconnect(libdbusConnection, false);

    auto dispatchThread = std::thread(&dispatch, libdbusConnection);

    ::DBusMessage* libdbusMessageCall = dbus_message_new_method_call(
                    "org.freedesktop.DBus",
                    "/org/freedesktop/DBus",
                    "org.freedesktop.DBus",
                    "ListNames");

    dbus_message_set_signature(libdbusMessageCall, "");

    DBusPendingCall* libdbusPendingCall;

    dbus_connection_send_with_reply(
                    libdbusConnection,
                    libdbusMessageCall,
                    &libdbusPendingCall,
                    500);

    dbus_pending_call_set_notify(
                    libdbusPendingCall,
                    notifyThunk,
                    libdbusConnection,
                    NULL);

    ASSERT_EQ(true, future.get());
    dispatchThread.join();
}
예제 #10
0
BOOST_AUTO_TEST_CASE(future, *boost::unit_test::timeout(15))
{
    using boost::unit_test::framework::master_test_suite;

    boost::asio::io_context ios;

    std::future<int> fut = bp::async_system(
                              ios, boost::asio::use_future,
                              master_test_suite().argv[1],
                              "test", "--exit-code", "42");

    ios.run();

    int exit_code = 0;
    BOOST_CHECK_NO_THROW(exit_code = fut.get());

    BOOST_CHECK_EQUAL(exit_code, 42);
}

BOOST_AUTO_TEST_CASE(future_error, *boost::unit_test::timeout(15))
{
    using boost::unit_test::framework::master_test_suite;

    boost::asio::io_context ios;

    std::future<int> fut = bp::async_system(
                              ios, boost::asio::use_future,
                              "invalid-command");

    ios.run();
예제 #11
0
// return from thread
int getNum2(std::future<int> &f) {
  print("In getNum1");
  return f.get() + 10;
}
예제 #12
0
 /**
  * Check task for exceptions.
  *
  * If an exception happened in the task, re-throw it in this
  * thread. This will not do anything if there was no exception.
  */
 void check_for_exception() {
     if (m_future.valid() && m_future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
         m_future.get();
     }
 }
void test(std::future<int>& input) {
  std::cout << input.get() << std::endl;
}
예제 #14
0
파일: util.hpp 프로젝트: dforsi/libosmium
 inline void wait_until_done(std::future<T>& future) {
     if (future.valid()) {
         future.get();
     }
 }
예제 #15
0
파일: util.hpp 프로젝트: dforsi/libosmium
 inline void check_for_exception(std::future<T>& future) {
     if (future.valid() && future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
         future.get();
     }
 }
예제 #16
0
파일: main.cpp 프로젝트: wangmeijing/thread
void s(std::future<double>& fut)
{
    double x = fut.get();
    std::cout << " fut = " << x << std::endl;
}
예제 #17
0
  void hook_post_step()
  {
    parent_t::hook_post_step(); // includes output

    this->mem->barrier();

    if (this->rank == 0) 
    {
      // assuring previous async step finished ...
#if defined(STD_FUTURE_WORKS)
      if (
        params.async && 
        this->timestep != 0 && // ... but not in first timestep ...
        ((this->timestep - 1) % this->outfreq != 0) // ... and not after diag call
        //!((this->timestep-1) == 0 || ((this->timestep-1) % this->outfreq == 0 && (this->timestep-1) >= this->spinup)) // .. and not after diag
      ) {
        assert(ftr.valid());
        ftr.get();
      } else assert(!ftr.valid());
#endif

      // running synchronous stuff
      prtcls->step_sync(
        params.cloudph_opts,
        make_arrinfo(this->mem->advectee(ix::th)),
        make_arrinfo(this->mem->advectee(ix::rv))
      ); 

      // running asynchronous stuff
      {
        using libcloudphxx::lgrngn::particles_t;
        using libcloudphxx::lgrngn::CUDA;
        using libcloudphxx::lgrngn::multi_CUDA;

#if defined(STD_FUTURE_WORKS)
        if (params.async)
        {
          assert(!ftr.valid());

          if(params.backend == multi_CUDA)
            ftr = std::async(
              std::launch::async, 
              &particles_t<real_t, multi_CUDA>::step_async, 
              dynamic_cast<particles_t<real_t, multi_CUDA>*>(prtcls.get()),
              params.cloudph_opts
            );
          else if(params.backend == CUDA)
            ftr = std::async(
              std::launch::async, 
              &particles_t<real_t, CUDA>::step_async, 
              dynamic_cast<particles_t<real_t, CUDA>*>(prtcls.get()),
              params.cloudph_opts
            );
          assert(ftr.valid());
        } else 
#endif
          prtcls->step_async(params.cloudph_opts);
      }

      // performing diagnostics
      //if (this->timestep == 0 || (this->timestep % this->outfreq == 0 && this->timestep >= this->spinup))
      if (this->timestep % this->outfreq == 0) 
      { 
#if defined(STD_FUTURE_WORKS)
        if (params.async)
        {
          assert(ftr.valid());
          ftr.get();
        }
#endif
        diag();
      }
    }

    this->mem->barrier();
  }
예제 #18
0
  int testnum = 100;
  int testnum2 = 1000;
  int testnum3 = 10000;
  string teststr = "asdf";

  std::future<int> ret1 = tp.AddTask(IncreNum, 120 );
  std::future<void> ret2 = tp.AddTask(test2, teststr );
  std::future<int> ret3 = tp.AddTask(FindPrime, 1000);
  typedef decltype(FindPrime(10000)) retType;
  std::future< retType > ret4 = tp.AddTask(FindPrime, 10000);
  std::future<void> ret5 = tp.AddTask(IncreNumRefSelfTask, ptp, std::ref(testnum));

  tp.RunThreads();

  int primes1 = ret3.get();
  retType  primes2 = ret4.get();
  ret5.get();
  int increRet = ret1.get();
  cout<<"Number of primes under 1000: "<<primes1<<endl;
  cout<<"Number of primes under 10000: "<<primes2<<endl;

  SECTION( "Task Results" ) {
    CHECK( primes1 == 168 );
    CHECK( primes2 == 1229 );
    CHECK( testnum == 102 );
    CHECK( increRet == 121 );
  }

  std::this_thread::sleep_for(std::chrono::milliseconds(2000));
  
예제 #19
0
/***  http://www.cnblogs.com/haippy/p/3280643.html
promise对象可以保存某一类型T的值,该值可被future对象读取(可能在另外一个线程中),因此promise也提供了一种线程同步的手段。
在promise对象构造时可以和一个共享状态(通常是std::future)相关联,并可以在相关联的共享状态(std::future)上保存一个类型为 T 的值。
可以通过 get_future 来获取与该 promise 对象相关联的 future 对象,调用该函数之后,两个对象共享相同的共享状态(shared state):
	promise 对象是异步 Provider,它可以在某一时刻设置共享状态的值。
	future 对象可以异步返回共享状态的值,或者在必要的情况下阻塞调用者并等待共享状态标志变为 ready,然后才能获取共享状态的值。
***/
void print_int(std::future<int>& fut) {
	int x = fut.get(); // 获取共享状态的值.
	std::cout << "value: " << x << '\n'; // value: 10.
}
void helper(std::future<void>& task, ray_tracing::Semaphore& semaphore)
{
    task.get();
    semaphore.increase();
}
예제 #21
0
void thread_pool::handle_task(std::future<void> f) {
	f.get();
}
예제 #22
0
 void gridding_barrier() {
     if (gridding_future.valid())
         gridding_future.get(); //Block until result becomes available
 }