void beat() { static ServerInfo info; info = Server->getInfo(); static thread hb; if(hb.timed_join(milliseconds(0))) { hb = thread( doHeartBeat,std::ref(info)); Tasks->callLater(60000,beat); } }
// Init() needs to be separate so that shared_from_this can give the shared_ptr to the workers in do_async_accept() without exploding everything // It's weird, but it works. Read the docs on boost::weak_ptr and enable_shared_from_this for more information. void BasicService::init() { // Initialize presalted hash state signing_key_length = 2048; signing_key = Platform::getRandomBytes(signing_key_length); // Bind and open acceptor socket srv_acceptor.open(srv_endpoint.protocol()); srv_acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); srv_acceptor.bind(srv_endpoint); srv_acceptor.listen(); srv_endpoint = srv_acceptor.local_endpoint(); FBLOG_INFO("HTTP:Service", "Started server on " << srv_endpoint.port()); do_async_accept(); // Start worker threadpool. for (std::size_t i = 0; i < threadpool_size; ++i) { shared_ptr<boost::thread> thread(new boost::thread(boost::bind(&BasicService::_worker_thread_entry, this))); threadpool.push_back(thread); } }
int main() { boost::asio::io_service io_service; boost::asio::deadline_timer timer(io_service); timer.expires_at(boost::posix_time::pos_infin); boost::atomic_bool shutdown(false); int num_events = 0; auto waiter = [&timer, &num_events, &shutdown](boost::asio::yield_context context) { while (!shutdown) { std::cout << "waiting on event" << std::endl; boost::system::error_code e; timer.async_wait(context[e]); std::cout << "got event (" << e.message() << ")" << std::endl; ++num_events; } }; boost::asio::spawn(io_service, std::move(waiter)); boost::thread thread(boost::bind(&boost::asio::io_service::run, &io_service)); for (auto i = 0; i < 5000; ++i) { io_service.post([&timer, i]{ std::cout << i << std::endl; timer.cancel(); }); } io_service.post([&]{ shutdown = true; timer.cancel(); }); thread.join(); std::cout << "Check: " << num_events << " events counted\n"; }
virtual void Start(){ _thr = thread(&TObj::Run, this); _thr.join(); }
void Start(){ _thr = thread(bind(&srv::Run,this)); _thr.join(); }