void testThreadPool(){ auto fun = [](float wTime, XTime::TIMER_LEVEL level) { std::thread::id tid = std::this_thread::get_id(); XTime::startTimer(5, wTime,[=]{ std::string des = ""; switch (level) { case XTime::TIMER_LEVEL::L_SECOND: des = "seconds"; break; case XTime::TIMER_LEVEL::L_MILLION: des = "milliseconds"; break; case XTime::TIMER_LEVEL::L_MICRO: des = "microseconds"; break; default: break; } LOG_I("this is a %s timer ,thread_id=%s",des.c_str(),XString::convert<std::string>(tid).c_str()); },XTime::TIMER_LEVEL::L_MILLION); return wTime; }; auto pool = std::unique_ptr<XThreadPool>(new XThreadPool(2)); pool->async([=]{fun(1,XTime::TIMER_LEVEL::L_SECOND);}); pool->async([=]{fun(0.001,XTime::TIMER_LEVEL::L_MILLION);}); pool->async([=]{fun(0.001,XTime::TIMER_LEVEL::L_MICRO);}); pool->async([=](int x, int y){ LOG_I("%d + %d = %d",x,y,x+y); return x+y; }, 10,11); }
int main (int argc, char ** argv) { printf("Call Init\n"); hclib_init(&argc, argv); int i = 0; // This is ok to have these on stack because this // code is alive until the end of the program. int indices [NB_ASYNC]; init_ran(ran, NB_ASYNC); while(i < NB_ASYNC) { indices[i] = i; //Note: Forcefully pass the address we want to write to as a void ** async(async_fct, (void*) (indices+i), NULL, NULL, NO_PROP); i++; } printf("Call Finalize\n"); hclib_finalize(); printf("Check results: "); i=0; while(i < NB_ASYNC) { assert(ran[i] == i); i++; } printf("OK\n"); return 0; }
bool NicerConnection::setRemoteCandidates(const std::vector<CandidateInfo> &candidates, bool is_bundle) { std::vector<CandidateInfo> cands(candidates); auto remote_candidates_promise = std::make_shared<std::promise<void>>(); nr_ice_peer_ctx *peer = peer_; nr_ice_media_stream *stream = stream_; std::shared_ptr<NicerInterface> nicer = nicer_; async([cands, is_bundle, nicer, peer, stream, this, remote_candidates_promise] { ELOG_DEBUG("%s message: adding remote candidates (%ld)", toLog(), cands.size()); for (const CandidateInfo &cand : cands) { std::string sdp = cand.sdp; std::size_t pos = sdp.find(","); std::string candidate = sdp.substr(0, pos); ELOG_DEBUG("%s message: New remote ICE candidate (%s)", toLog(), candidate.c_str()); UINT4 r = nicer->IcePeerContextParseTrickleCandidate(peer, stream, const_cast<char *>(candidate.c_str())); if (r && r != R_ALREADY) { ELOG_WARN("%s message: Couldn't add remote ICE candidate (%s) (%d)", toLog(), candidate.c_str(), r); } } remote_candidates_promise->set_value(); }); std::future<void> remote_candidates_future = remote_candidates_promise->get_future(); std::future_status status = remote_candidates_future.wait_for(std::chrono::seconds(1)); if (status == std::future_status::timeout) { ELOG_WARN("%s message: Could not set remote candidates", toLog()); return false; } return true; }
shared_future<int64_t>StdStreamAdapter::ReadAsync(uint8_t *pbBuffer, int64_t cbBuffer, int64_t cbOffset, launch launchType) { auto selfPtr = shared_from_this(); return async(launchType, [](shared_ptr<StdStreamAdapter>self, uint8_t *buffer, int64_t size, int64_t offset) -> int64_t { // first lock object lock_guard<mutex>lock(*self->m_locker); if (self->m_iBackingStream.get() != nullptr) { self->m_iBackingStream->clear(); self->m_iBackingStream->seekg(offset); } else { // unavailable throw exceptions::RMSCryptoIOException( exceptions::RMSCryptoIOException::OperationUnavailable, "Operation unavailable!"); } auto ret = static_cast<int64_t>(self->ReadInternal(buffer, size)); return ret; }, selfPtr, pbBuffer, cbBuffer, cbOffset); }
/// Direct access to last record. Record lastRecord() const { return async([this] { assert(!_records.empty()); return _records.back(); }).value(); }
void Client::clientConnect( const char* in ){ unsigned long ip; char str[128] = "Connecting to "; ip = inet_addr(in); if (ip == INADDR_ANY || ip == INADDR_NONE){ onError("You have entered an invalid IP. Example of a valid IP: 83.72.95.125"); }else{ strcat(str, in); onError(str); data->serverAddress.sin_family = AF_INET; data->serverAddress.sin_port = htons(1313); #ifdef _WIN32 data->serverAddress.sin_addr.S_un.S_addr = ip; #else data->serverAddress.sin_addr.s_addr = ip; #endif if( ::connect( data->serverSocket, (sockaddr*)(&data->serverAddress), sizeof(sockaddr_in) ) != 0){ onError("Error connecting"); }else{ onError("Connected successfully!"); //ReciverThread *r = new ReciverThread(serverSocket); //r->start(); //connection.reset(r); connection = async(this, &Client::reciever, 0 ); connected = true; } } }
Future<GitRepo *> GitRepo::clone(const QDir &dir, const QUrl &url) { return async([dir, url](Notifier notifier) { initGit(); notifier.status("Cloning %1..." % url.toString()); std::unique_ptr<GitRepo> repo = std::make_unique<GitRepo>(dir); GitPayload payload{notifier}; git_clone_options opts = GIT_CLONE_OPTIONS_INIT; opts.checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE | GIT_CHECKOUT_USE_THEIRS; opts.checkout_opts.progress_cb = &gitCheckoutNotifier; opts.checkout_opts.progress_payload = &payload; opts.fetch_opts.callbacks.transfer_progress = &gitFetchNotifier; opts.fetch_opts.callbacks.payload = &payload; opts.fetch_opts.callbacks.credentials = &credentialsCallback; repo->m_repo = GitResource<git_repository>::create(&git_clone, &git_repository_free, url.toString().toLocal8Bit(), dir.absolutePath().toLocal8Bit(), &opts); return repo.release(); }); }
future<bool>StdStreamAdapter::FlushAsync(launch launchType) { auto selfPtr = shared_from_this(); return async(launchType, [](shared_ptr<StdStreamAdapter>self) -> bool { return self->Flush(); }, selfPtr); }
void testbar() { long i; double meantime, sd; int indices[nthreads]; phaser_t ph; phaser_create(&ph, SIGNAL_WAIT, degree); start_finish(); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing PHASER BARRIER time\n"); for(i = 1; i < nthreads; ++i) { indices[i] = i; async(&barrier_test, (void *) (indices+i), NULL, NULL, PHASER_TRANSMIT_ALL); } indices[0] = 0; barrier_test((void *) indices); end_finish(); phaser_drop(ph); stats (&meantime, &sd); printf("BARRIER time = %f microseconds +/- %f\n", meantime, CONF95*sd); printf("BARRIER overhead = %f microseconds +/- %f\n", meantime-reftime, CONF95*(sd+refsd)); }
/// Waits for the given number of records to be reached, before the given timeout. qi::FutureSync<bool> waitUntil(unsigned int nofRecords, const qi::Duration& timeout) const { qi::Promise<bool> waiting; async([this, waiting, nofRecords, timeout]() mutable { if(nofRecords <= _records.size()) { waiting.setValue(true); return; } qi::SignalLink recordedSubscription; // track timeout auto timingOut = asyncDelay([this, waiting, &recordedSubscription]() mutable { waiting.setValue(false); recorded.disconnect(recordedSubscription); }, timeout); // be called after signal emissions are recorded recordedSubscription = recorded.connect(stranded( [this, waiting, &recordedSubscription, timingOut, nofRecords]() mutable { if (nofRecords <= _records.size()) { waiting.setValue(true); timingOut.cancel(); recorded.disconnect(recordedSubscription); } // no need for scheduling in the strand because it is a direct connection })).setCallType(qi::MetaCallType_Direct); }); return waiting.future(); }
shared_future<int64_t>StdStreamAdapter::WriteAsync(const uint8_t *cpbBuffer, int64_t cbBuffer, int64_t cbOffset, launch launchType) { auto selfPtr = shared_from_this(); return async(launchType, [](shared_ptr<StdStreamAdapter>self, const uint8_t *buffer, int64_t size, int64_t offset) -> int64_t { // first lock object lock_guard<mutex>lock(*self->m_locker); // seek to position and write if (self->m_oBackingStream.get() != nullptr) { self->m_oBackingStream->seekp(offset); } else { // unavailable throw exceptions::RMSCryptoIOException( exceptions::RMSCryptoIOException::OperationUnavailable, "Operation unavailable!"); } int64_t ret = 0; try { ret = static_cast<int64_t>(self->WriteInternal(buffer, size)); } catch (exception& e) { throw e; } return ret; }, selfPtr, cpbBuffer, cbBuffer, cbOffset); }
CandidatePair NicerConnection::getSelectedPair() { auto selected_pair_promise = std::make_shared<std::promise<CandidatePair>>(); async([this, selected_pair_promise] { nr_ice_candidate *local; nr_ice_candidate *remote; nicer_->IceMediaStreamGetActive(peer_, stream_, 1, &local, &remote); CandidatePair pair; if (!local || !remote) { selected_pair_promise->set_value(CandidatePair{}); return; } pair.clientCandidateIp = getStringFromAddress(remote->addr); pair.erizoCandidateIp = getStringFromAddress(local->addr); pair.clientCandidatePort = getPortFromAddress(remote->addr); pair.erizoCandidatePort = getPortFromAddress(local->addr); pair.clientHostType = getHostTypeFromNicerCandidate(remote); pair.erizoHostType = getHostTypeFromNicerCandidate(local); ELOG_DEBUG("%s message: Client Host Type %s", toLog(), pair.clientHostType.c_str()); selected_pair_promise->set_value(pair); }); std::future<CandidatePair> selected_pair_future = selected_pair_promise->get_future(); std::future_status status = selected_pair_future.wait_for(std::chrono::seconds(1)); CandidatePair pair = selected_pair_future.get(); if (status == std::future_status::timeout) { ELOG_WARN("%s message: Could not get selected pair", toLog()); return CandidatePair{}; } return pair; }
void Director::cue() { sharedFut = async(launch::async, [&]{ scriptsIter iter = scripts.begin(); while (iter != scripts.end()) { sIter sIt = iter->second.begin(); while (sIt != iter->second.end()) { play->checkAvailable(maximum); for (int i = 0; i < maximum; i++) { if (!players[i]->isbusy()) { try { players[i]->enter(iter->first, sIt->first, sIt->second); } catch (CodeException& e) { // if there is an exception, need to stop all the currently running threads emergencyStop(); throw e; } break; } } sIt++; } iter++; } finished.set_value(true); for (int i = 0; i < maximum; i++) { players[i]->join(); } return true; }).share(); }
result_type operator()(ast::score& score) { if (!score.time_sigs.empty()) global_time_signature = score.time_sigs.front(); { std::vector<std::future<bool>> staves; for (ast::part &part: score.parts) { if (!part.empty()) { std::size_t const staff_count{part.front().paragraphs.size()}; for (std::size_t staff_index = 0; staff_index < staff_count; ++staff_index) { staves.emplace_back ( async( std::launch::async , std::move(annotate_staff<ErrorHandler>( error_handler , report_error , global_time_signature , score.key_sig )) , staff_index, std::ref(part)) ); } } } if (!all_of( begin(staves), end(staves) , mem_fun_ref(&std::future<bool>::get))) return false; } return unfold(score); }
void runFunction(const oclm::program& p, const int& numThreads, const std::string& function) { // Select a kernel oclm::kernel k(p, function); // build a function object out of the kernel oclm::function f = k[oclm::global(numThreads), oclm::local(1)]; std::vector<int> A(numThreads, 1); std::vector<int> B(numThreads, 2); std::vector<int> C(numThreads, 0); // create a command queue with a device type and a platform ... context and // platform etc is selected in the background ... this will be managed as // global state oclm::command_queue queue(oclm::device::default_, false); // asynchronously fire the opencl function on the command queue, the // std::vector's will get copied back and forth transparantly, policy classes // to come ... oclm::event e1 = async(queue, f(A, B, C)); // wait until everything is completed ... e1.get(); }
void test1() { // this one works // most fundimental form: std::cout << __FILE__ << ":" << __LINE__ << std::endl; boost::unique_future<int> fi= async (&calculate_the_answer_to_life_the_universe_and_everything); int i= fi.get(); BOOST_TEST (i== 42); // This one chokes at compile time std::cout << __FILE__ << ":" << __LINE__ << std::endl; boost::unique_future<size_t> fut_1= async (&foo, "Life"); BOOST_TEST (fut_1.get()== 4); }
// -------------------------------------------------------------------------------------------------------------------- void window::builder::position(int x, int y) { _post.push_back(async(launch::deferred, [this, x, y]() -> int { this->_win->position(x, y); return 0; })); }
Future<void> GitRepo::submodulesUpdate(const bool init) const { return async([this, init](Notifier notifier) { GitPayload payload{notifier, QString(), init}; GitException::checkAndThrow(git_submodule_foreach(m_repo, &gitSubmoduleUpdate, &payload)); }); }
Future<void> GitRepo::pull(const QString &id) const { return async([this, id](Notifier notifier) { notifier.await(fetch()); notifier.await(checkout(id)); }); }
void future_prod(futures *fptr){ int i=120; //for(i=0;i<4;i++){ // future_set(fptr,i); //} async(fptr,generatedata); }
Future<void> GitSubmoduleSetupStep::perform(const ActionContext &ctxt) { return async([ctxt](Notifier notifier) { Git::GitRepo *repo = notifier.await(Git::GitRepo::open(ctxt.get<InstallContextItem>().buildDir)); notifier.await(repo->submodulesUpdate()); }); }
boost::unique_future<typename boost::result_of< F(A1) >::type> async (F&& f, A1&& a1) { std::cout << __FILE__ << ":" << __LINE__ << std::endl; // This should be all it needs. But get a funny error deep inside Boost. // problem overloading with && ? return async (boost::bind(f,a1)); }
int main() { auto ftr = async(&func); std::cout << "Hello from main!" << std::endl; std::string str = ftr.get(); std::cout << str << std::endl; return 0; }
void main_loop(dispatch::function main_loop_function) { auto main_queue = queue::main_queue(); while (!thread_pool::shared_pool()->stop) { main_queue->async(main_loop_function); process_main_loop(); } }
void QDispatchGroup::async( QRunnable *r, const xdispatch::queue &q ) { Q_ASSERT( r ); async( new RunnableOperation( r ), q ); }
void NicerConnection::start() { async([this] { startSync(); }); std::future_status status = start_promise_.get_future().wait_for(std::chrono::seconds(5)); if (status == std::future_status::timeout) { ELOG_WARN("%s Start timed out", toLog()); } }
void DailyForecast(wstring city) { WeatherInfo weather; int c = 0; ShowCursor(); while (c < 1 || c > 16) { cls(); Center(32, true); cout << "Input number of days to show(1-16): "; string temp; cin >> temp; if (!((temp[0] < 48 || temp[0] > 57) && (temp[1] < 48 || temp[0] > 57))) c = stoi(temp.substr(0,2)); } HideCursor(); wchar_t count[3]; _itow_s(c, count, 10); auto result(async(SendRequest, L"forecast/daily?q=" + city + L"&cnt=" + count)); cls(); Center(16, true); cout << "Fetching data"; cursorPos = getCursorPos(); for (int i = 0; result.wait_for(span) != future_status::ready; i++) { SetConsoleCursorPosition(ConsoleH, cursorPos); switch (i % 4) { case 0: cout << " "; break; case 1: cout << ". "; break; case 2: cout << ".. "; break; case 3: cout << "..."; } if (i > 50) { Center(16, true); cout << " Fetch failed "; SetConsoleTextAttribute(ConsoleH, 240); Center(4, 4); cout << "Back"; SetConsoleTextAttribute(ConsoleH, 15); while (_getch() != 13); return; } } weather = ParseDaily(result.get()); auto weatherI = DayMenu(weather); if (weatherI.main == "back") return; PrintDaily(weatherI, weather.cityName); }
impl( const config& c) : cfg( c ) { if( cfg.rotate ) { FC_ASSERT( cfg.rotation_interval >= seconds( 1 ) ); FC_ASSERT( cfg.rotation_limit >= cfg.rotation_interval ); _rotation_task = async( [this]() { rotate_files( true ); }, "rotate_files(1)" ); } }
/// The number of records. size_t recordCount() const { qiLogDebug("qi.signalspy") << "Getting record count " << (strand()->isInThisContext() ? "from strand" : "from outside"); return async([this] { qiLogDebug("qi.signalspy") << "Getting record count"; return _records.size(); }).value(); }
void Notes::Upload(osm::OsmOAuth const & auth) { // Capture self to keep it from destruction until this thread is done. auto const self = shared_from_this(); auto const doUpload = [self, auth]() { size_t size; { lock_guard<mutex> g(self->m_mu); size = self->m_notes.size(); } osm::ServerApi06 api(auth); auto it = begin(self->m_notes); for (size_t i = 0; i != size; ++i, ++it) { try { auto const id = api.CreateNote(it->m_point, it->m_note); LOG(LINFO, ("A note uploaded with id", id)); } catch (osm::ServerApi06::ServerApi06Exception const & e) { LOG(LERROR, ("Can't upload note.", e.Msg())); // We believe that next iterations will suffer from the same error. return; } lock_guard<mutex> g(self->m_mu); it = self->m_notes.erase(it); ++self->m_uploadedNotesCount; Save(self->m_fileName, self->m_notes, self->m_uploadedNotesCount); } }; // Do not run more than one upload thread at a time. static auto future = async(launch::async, doUpload); auto const status = future.wait_for(milliseconds(0)); if (status == future_status::ready) future = async(launch::async, doUpload); }