TEST_F(PeriodicActionPoolTest, basics) { PeriodicActionPool::Ptr pool(PeriodicActionPool::create("TestPool", nthreads_)); const size_t iterations = 10; size_t count = 0; boost::promise<bool> promise; boost::unique_future<bool> future(promise.get_future()); auto fun([&]() -> PeriodicActionContinue { if (++count == iterations) { promise.set_value(true); } return PeriodicActionContinue::T; }); std::atomic<uint64_t> period(10); std::unique_ptr<PeriodicActionPool::Task> t(pool->create_task("counter", std::move(fun), period, false)); EXPECT_TRUE(future.get()); }
bool execute_insert(CassSession* session, const std::string& table_name) { std::string query = str(boost::format("INSERT INTO %s (id, event_time, text_sample) VALUES (?, ?, ?)") % table_name); test_utils::CassStatementPtr statement(cass_statement_new(query.c_str(), 3)); // Determine if bound parameters can be used based on C* version if (version.major == 1) { test_utils::CassPreparedPtr prepared = test_utils::prepare(session, query.c_str()); statement = test_utils::CassStatementPtr(cass_prepared_bind(prepared.get())); } boost::chrono::system_clock::time_point now(boost::chrono::system_clock::now()); boost::chrono::milliseconds event_time(boost::chrono::duration_cast<boost::chrono::milliseconds>(now.time_since_epoch())); std::string text_sample(test_utils::string_from_time_point(now)); cass_statement_bind_uuid(statement.get(), 0, test_utils::generate_time_uuid(uuid_gen)); cass_statement_bind_int64(statement.get(), 1, event_time.count()); cass_statement_bind_string(statement.get(), 2, text_sample.c_str()); test_utils::CassFuturePtr future(cass_session_execute(session, statement.get())); cass_future_wait(future.get()); CassError code = cass_future_error_code(future.get()); if (code != CASS_OK && code != CASS_ERROR_LIB_REQUEST_TIMED_OUT) { // Timeout is okay CassString message; cass_future_error_message(future.get(), &message.data, &message.length); fprintf(stderr, "Error occurred during insert '%.*s'\n", static_cast<int>(message.length), message.data); return false; } return true; }
bool select_task(const std::string& query, CassConsistency consistency, int num_iterations) { bool is_successful = true; test_utils::CassStatementPtr statement(cass_statement_new(query.c_str(), 0)); cass_statement_set_consistency(statement.get(), consistency); for (int i = 0; i < num_iterations; ++i) { test_utils::CassFuturePtr future(cass_session_execute(session, statement.get())); cass_future_wait(future.get()); CassError code = cass_future_error_code(future.get()); if (code != CASS_OK && code != CASS_ERROR_LIB_REQUEST_TIMED_OUT && code != CASS_ERROR_SERVER_READ_TIMEOUT) { // Timeout is okay CassString message; cass_future_error_message(future.get(), &message.data, &message.length); fprintf(stderr, "Error occurred during select '%.*s'\n", static_cast<int>(message.length), message.data); is_successful = false; } if (code == CASS_OK) { test_utils::CassResultPtr result(cass_future_get_result(future.get())); if (cass_result_row_count(result.get()) == 0) { fprintf(stderr, "No rows returned from query\n"); is_successful = false; } } } return is_successful; }
TEST_F(PeriodicActionPoolTest, cancellation) { PeriodicActionPool::Ptr pool(PeriodicActionPool::create("TestPool", nthreads_)); boost::promise<bool> promise; boost::unique_future<bool> future(promise.get_future()); bool running = false; auto fun([&]() -> PeriodicActionContinue { if (not running) { promise.set_value(true); running = true; } return PeriodicActionContinue::T; }); std::atomic<uint64_t> period(3600); std::unique_ptr<PeriodicActionPool::Task> t(pool->create_task("LongPeriod", std::move(fun), period, true)); EXPECT_TRUE(future.get()); }
void Plugins::_unload(const QString &id, Future<bool> *f) { QSharedPointer<Future<bool> > future(f); LOG_DEBUG("Unloading the plugin", Properties("id", id), "Plugins", "_unload"); Mutex mutex(this->mutex, "Plugins", "_unload"); if (!mutex) return ; if (!this->plugins.contains(id)) { LOG_WARNING("The plugin is already unloaded or does not exist", Properties("id", id), "Plugins", "_unload"); return ; } if (this->plugins.value(id)->getState() != LightBird::IPlugins::LOADED) { LOG_WARNING("The plugin is already unloading", Properties("id", id), "Plugins", "_unload"); return ; } Extensions::instance()->remove(this->plugins.value(id)); if (!this->plugins.value(id)->unload()) { LOG_ERROR("Unable to unload the plugin", Properties("id", id), "Plugins", "_unload"); return ; } if (this->plugins.value(id)->getState() == LightBird::IPlugins::UNLOADED) { delete this->plugins.value(id); this->plugins.remove(id); this->orderedPlugins.removeAll(id); Events::instance()->send("plugin_unloaded", id); LOG_INFO("Plugin unloaded", Properties("id", id), "Plugins", "_unload"); } future->setResult(true); }
void Plugins::_install(const QString &id, Future<bool> *f) { LightBird::IPlugins::State state; QSharedPointer<Future<bool> > future(f); LOG_DEBUG("Installing the plugin", Properties("id", id), "Plugins", "_install"); Mutex mutex(this->mutex, "Plugins", "_install"); if (!mutex) return ; if (this->unloadAllPlugins) { LOG_WARNING("No plugins can be installed, because all plugins are unloading.", Properties("id", id), "Plugins", "_install"); return ; } if ((state = this->_getState(id)) != LightBird::IPlugins::UNINSTALLED) { LOG_WARNING(state != LightBird::IPlugins::UNKNOW ? "The plugin is already installed" : "The plugin is unknow", Properties("id", id).add("state", QString::number(state)), "Plugins", "_install"); return ; } Plugin plugin(id); if (!plugin.load(false)) { LOG_WARNING("Unable to load the plugin in order to install it", Properties("id", id), "Plugins", "_install"); return ; } if (!plugin.install()) { LOG_WARNING("Unable to install the plugin", Properties("id", id), "Plugins", "_install"); return ; } Events::instance()->send("plugin_installed", id); LOG_INFO("Plugin installed", Properties("id", id), "Plugins", "_install"); future->setResult(true); }
int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if (0 == prices.size()) { return 0; } std::vector<int> history(prices.size(), 0), future(prices.size(), 0); int valley = prices[0]; for (int i = 0; i < prices.size(); ++ i) { valley = std::min(valley, prices[i]); if (i > 0) { history[i] = std::max(history[i - 1], prices[i] - valley); } } int peak = prices[prices.size() - 1], max = 0; for (int i = prices.size() - 1; i >= 0; -- i) { peak = std::max(peak, prices[i]); if (i < prices.size() - 1) { future[i] = std::max(future[i + 1], peak - prices[i]); } max = std::max(max, history[i] + future[i]); } return max; }
void build(const std::string& ip_prefix, int num_nodes) { test_utils::CassClusterPtr cluster(cass_cluster_new()); test_utils::initialize_contact_points(cluster.get(), ip_prefix, num_nodes, 0); cass_cluster_set_load_balance_round_robin(cluster.get()); cass_cluster_set_token_aware_routing(cluster.get(), cass_false); test_utils::CassSessionPtr session(test_utils::create_session(cluster.get())); for (int i = 0; i < num_nodes; ++i) { test_utils::CassStatementPtr statement( cass_statement_new("SELECT tokens, data_center FROM system.local", 0)); test_utils::CassFuturePtr future(cass_session_execute(session.get(), statement.get())); test_utils::wait_and_check_error(future.get()); test_utils::CassResultPtr result(cass_future_get_result(future.get())); const CassRow* row = cass_result_first_row(result.get()); const CassValue* data_center = cass_row_get_column_by_name(row, "data_center"); const CassValue* token_set = cass_row_get_column_by_name(row, "tokens"); CassString str; cass_value_get_string(data_center, &str.data, &str.length); std::string dc(str.data, str.length); std::string ip = cass::get_host_from_future(future.get()); test_utils::CassIteratorPtr iterator(cass_iterator_from_collection(token_set)); while (cass_iterator_next(iterator.get())) { cass_value_get_string(cass_iterator_get_value(iterator.get()), &str.data, &str.length); std::string token(str.data, str.length); tokens[boost::lexical_cast<int64_t>(token)] = Host(ip, dc); } } }
CassFuture* cass_session_prepare_n(CassSession* session, const char* query, size_t query_length) { cass::Future::Ptr future(session->prepare(query, query_length)); future->inc_ref(); return CassFuture::to(future.get()); }
// Simplified version for public release bool CCCHLogicalChannel::processPages() { while (NewPagingEntry *npe1 = gPagingQ.mPageQ.readNoBlock()) { LOG(DEBUG)<<LOGVAR(npe1); if (npe1->mGprsClient) { // Is it a GPRS page? // Add 51 to the frame time because the message because the MS may be on the other 51-multiframe. Time future(mCcchNextWriteTime + 52); if (! sendGprsCcchMessage(npe1,future)) { delete npe1; // In the incredibly unlikely event that the above failed, just give up. continue; } } else { const L3MobileIdentity& id1 = npe1->getMobileId(); ChannelType type1 = npe1->getGsmChanType(); L3PagingRequestType1 page1(id1,type1); L2LogicalChannelBase::l2sendm(page1,L3_UNIT_DATA); } if (++npe1->mSendCount < 2) { // Send each page twice. gPagingQ.mPageQ.write_front(npe1); // Put it back for resend in the next multiframe. } else { delete npe1; } return true; } return false; // CCCH unused. }
/** * Execute a query on the system table * * @param is_async True if async query; false otherwise */ void execute_query(bool is_async = false) { std::string query = "SELECT * FROM system.local"; test_utils::CassStatementPtr statement(cass_statement_new_n(query.data(), query.size(), 0)); test_utils::CassFuturePtr future(cass_session_execute(session_.get(), statement.get())); if (!is_async) { test_utils::wait_and_check_error(future.get()); } }
// Adds a task to the work queue. Call blocks until there is an available thread. void QueueTask(TaskType task) { WaitForAvailableThread(); typedef boost::packaged_task<Result> PackagedTask; boost::shared_ptr<PackagedTask> packaged_task_ptr = boost::make_shared<PackagedTask>(boost::bind(task)); io_service_.post(boost::bind(&PackagedTask::operator(), packaged_task_ptr)); boost::shared_future<Result> future(packaged_task_ptr->get_future()); futures_.push_back(future); }
/** * Prepare all queries on a given session. * * @param session The session to prepare the queries on */ void prepare_all_queries(test_utils::CassSessionPtr session) { for (std::vector<std::string>::const_iterator it = prepared_queries_.begin(); it != prepared_queries_.end(); ++it) { test_utils::CassFuturePtr future(cass_session_prepare(session.get(), it->c_str())); BOOST_REQUIRE_EQUAL(cass_future_error_code(future.get()), CASS_OK); } }
QList<CapabilityEntry> DbusCapabilitiesAdapter::lookup( const QString& participantId, const DiscoveryQos& discoveryQos ) { dbusSkeletonWrapper->logMethodCall("lookup", "DbusCapabilitiesAdapter"); QSharedPointer<DummyDbusCapabilitiesFuture> future(new DummyDbusCapabilitiesFuture()); localCapabilitiesDirectory.getCapabilities(participantId, future, discoveryQos); return future->get(discoveryQos.getDiscoveryTimeout()); }
/** * Execute a select statement against the system tables for a specified amount * of time. * * NOTE: Results and errors are ignored * * @param duration Duration in seconds to execute queries * @param session Session instance */ void execute_system_query(int duration, test_utils::CassSessionPtr session) { boost::posix_time::ptime start = boost::posix_time::second_clock::universal_time(); while ((boost::posix_time::second_clock::universal_time() - start).total_seconds() < duration) { test_utils::CassStatementPtr statement(cass_statement_new("SELECT * FROM system.local", 0)); cass_statement_set_consistency(statement.get(), CASS_CONSISTENCY_ONE); test_utils::CassFuturePtr future(cass_session_execute(session.get(), statement.get())); cass_future_wait_timed(future.get(), test_utils::ONE_SECOND_IN_MICROS); } }
Future::Ptr Session::prepare(const char* statement, size_t length) { PrepareRequest::Ptr prepare(new PrepareRequest(std::string(statement, length))); ResponseFuture::Ptr future(new ResponseFuture(metadata_.schema_snapshot(protocol_version(), cassandra_version()))); future->prepare_request = PrepareRequest::ConstPtr(prepare); execute(RequestHandler::Ptr(new RequestHandler(prepare, future, this))); return future; }
void cass_session_free(CassSession* session) { // This attempts to close the session because the joining will // hang indefinitely otherwise. This causes minimal delay // if the session is already closed. cass::SharedRefPtr<cass::Future> future(new cass::SessionFuture()); session->close_async(future.get(), true); future->wait(); delete session->from(); }
ThreadPool::Future ThreadPoolImpl::schedule(const Callable<void>& cb) { ThreadPool::Future future(new ThreadPool::Future::FutureImpl(cb)); log_debug("queue new task " << static_cast<void*>(future._impl->_callable)); _queue.put(future); log_debug("queue size " << _queue.size()); return future; }
//[callbacks_read_ec std::pair< AsyncAPI::errorcode, std::string > read_ec( AsyncAPI & api) { typedef std::pair< AsyncAPI::errorcode, std::string > result_pair; boost::fibers::promise< result_pair > promise; boost::fibers::future< result_pair > future( promise.get_future() ); // We promise that both 'promise' and 'future' will survive until our // lambda has been called. api.init_read([&promise]( AsyncAPI::errorcode ec, std::string const& data) mutable { promise.set_value( result_pair( ec, data) ); }); return future.get(); }
void PolicyTool::query(CassSession* session, int n, CassConsistency cl) { std::string select_query = str(boost::format("SELECT * FROM %s WHERE k = 0") % test_utils::SIMPLE_TABLE); for (int i = 0; i < n; ++i) { test_utils::CassStatementPtr statement(cass_statement_new_n(select_query.data(), select_query.size(), 0)); cass_statement_set_consistency(statement.get(), cl); test_utils::CassFuturePtr future(cass_session_execute(session, statement.get())); test_utils::wait_and_check_error(future.get()); add_coordinator(cass::get_host_from_future(future.get())); } }
void CCassandraLogAgent::executeUpdateLogStatement(StringBuffer& st) { cassSession->connect(); CassandraFuture futurePrep(cass_session_prepare_n(cassSession->querySession(), st.str(), st.length())); futurePrep.wait("prepare statement"); Owned<CassandraPrepared> prepared = new CassandraPrepared(cass_future_get_prepared(futurePrep), NULL); CassandraStatement statement(prepared.getClear()); CassandraFuture future(cass_session_execute(cassSession->querySession(), statement)); future.wait("execute"); cassSession->disconnect(); }
QList<CapabilityEntry> DbusCapabilitiesAdapter::lookup( const QString& domain, const QString& interfaceName, const types::ProviderQosRequirements& qos, const DiscoveryQos& discoveryQos ){ dbusSkeletonWrapper->logMethodCall("lookup", "DbusCapabilitiesAdapter"); QSharedPointer<DummyDbusCapabilitiesFuture> future(new DummyDbusCapabilitiesFuture()); localCapabilitiesDirectory.getCapabilities(domain,interfaceName, future, discoveryQos, qos); //this will block forever when no result is received. return future->get(discoveryQos.getDiscoveryTimeout()); }
BlobFuture Node::submitBlobForSending(QByteArray data, QString name) { OC_METHODGATE(); if(nullptr!=mBlobCourier) { BlobFuture future=mBlobCourier->submitSendingBlob(name,data); future.connect(*this); return future; } BlobFuture future(name); future.fail("No BLobCourier"); return future; }
bool CCassandraLogAgent::executeSimpleSelectStatement(const char* st, unsigned& resultValue) { CassandraStatement statement(cassSession->prepareStatement(st, getEspLogLevel()>LogNormal)); CassandraFuture future(cass_session_execute(cassSession->querySession(), statement)); future.wait("execute"); CassandraResult result(cass_future_get_result(future)); if (cass_result_row_count(result) == 0) return false; resultValue = getUnsignedResult(NULL, getSingleResult(result)); return true; }
void execute_query(CassSession* session, const std::string& query, CassResultPtr* result, CassConsistency consistency, cass_duration_t timeout) { CassStatementPtr statement(cass_statement_new(query.c_str(), 0)); cass_statement_set_consistency(statement.get(), consistency); CassFuturePtr future(cass_session_execute(session, statement.get())); wait_and_check_error(future.get(), timeout); if (result != NULL) { *result = CassResultPtr(cass_future_get_result(future.get())); } }
std::string get_replica(test_utils::CassSessionPtr session, const std::string& keyspace, const std::string& value) { // The query doesn't matter test_utils::CassStatementPtr statement( cass_statement_new("SELECT * FROM system.local", 1)); cass_statement_bind_string_n(statement.get(), 0, value.data(), value.size()); cass_statement_add_key_index(statement.get(), 0); cass_statement_set_keyspace(statement.get(), keyspace.c_str()); test_utils::CassFuturePtr future( cass_session_execute(session.get(), statement.get())); return cass::get_host_from_future(future.get()); }
bool execute_insert(CassStatement* statement) { test_utils::CassFuturePtr future(cass_session_execute(session, statement)); cass_future_wait(future.get()); CassError code = cass_future_error_code(future.get()); if (code != CASS_OK && code != CASS_ERROR_LIB_REQUEST_TIMED_OUT) { // Timeout is okay CassString message; cass_future_error_message(future.get(), &message.data, &message.length); fprintf(stderr, "Error occurred during insert '%.*s'\n", static_cast<int>(message.length), message.data); return false; } return true; }
bool TreeScanner::asyncScanForFiles(const Utils::FileName &directory) { if (!m_futureWatcher.isFinished()) return false; auto fi = new FutureInterface(); m_scanFuture = fi->future(); m_futureWatcher.setFuture(m_scanFuture); Utils::runAsync([this, fi, directory]() { TreeScanner::scanForFiles(fi, directory, m_filter, m_factory); }); return true; }
void game_display::display_unit_hex(map_location hex) { if (!hex.valid()) return; wb::future_map_if future(synced_context::get_synced_state() != synced_context::SYNCED); /**< Lasts for whole method. */ const unit *u = resources::gameboard->get_visible_unit(hex, dc_->teams()[viewing_team()], !dont_show_all_); if (u) { displayedUnitHex_ = hex; invalidate_unit(); } }
static void alter_schmea_version(void *arg) { ClusterInit* cluster_init = static_cast<ClusterInit*>(arg); test_utils::CassLog::reset("No schema agreement on live nodes after "); test_utils::CassStatementPtr schema_stmt(cass_prepared_bind(cluster_init->schema_alter_prepared.get())); boost::chrono::steady_clock::time_point end = boost::chrono::steady_clock::now() + boost::chrono::milliseconds(MAX_SCHEMA_AGREEMENT_WAIT_MS + 1000); // mess with system.peers for node 1 more than the wait time; targetting specific nodes do { cass_statement_bind_uuid(schema_stmt.get(), 0, test_utils::generate_random_uuid(cluster_init->inst.uuid_gen)); test_utils::CassFuturePtr future(cass_session_execute(cluster_init->schema_alter_session, schema_stmt.get())); cass_future_wait(future.get()); BOOST_REQUIRE_EQUAL(cass_future_error_code(future.get()), CASS_OK); } while (boost::chrono::steady_clock::now() < end && test_utils::CassLog::message_count() == 0); }