Differenze tra le versioni di "C++ Boost Asio Timer"

Da Andreabont's Wiki.
 
Riga 3: Riga 3:
 
== Compilare ==
 
== Compilare ==
 
<source lang="bash">
 
<source lang="bash">
g++ -std=c++11 <file_cpp> -lboost_system -pthread
+
g++ -std=c++14 <file_cpp> -lboost_system -pthread
 
</source>
 
</source>
  

Versione attuale delle 10:55, 28 gen 2020

Le Boost Asio sono delle librerie dedicate alla comunicazione di rete, esse forniscono una serie di gestione di eventi legati ai timer.

Compilare

g++ -std=c++14 <file_cpp> -lboost_system -pthread

Codice

Timer sincroni

#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

int main() {
    
    boost::asio::io_service io;

    boost::asio::deadline_timer timer(io, boost::posix_time::seconds(5));
    timer.wait();

    std::cout << "Hello, world!\n";

    return 0;

}

Timer asincroni

#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

int main() {
    
    boost::asio::io_service io;

    std::cout << "Start Timer 1" << std::endl;
    boost::asio::deadline_timer timer_1(io, boost::posix_time::seconds(10));
    timer_1.async_wait([](const boost::system::error_code& e){
        std::cout << "End Timer 1" << std::endl;
    });

    std::cout << "Start Timer 2" << std::endl;
    boost::asio::deadline_timer timer_2(io, boost::posix_time::seconds(5));
    timer_2.async_wait([](const boost::system::error_code& e){
        std::cout << "End Timer 2" << std::endl;
    });

    io.run();

    return 0;
    
}

Timer ricorrenti

#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <functional>

int main() {
    
    boost::asio::io_service io;

    std::cout << "Start Timer" << std::endl;
    
    boost::asio::deadline_timer timer(io, boost::posix_time::seconds(1));

    std::function<void(const boost::system::error_code&)> tick = [&timer,&tick](const boost::system::error_code& e){
        std::cout << "Tick" << std::endl;
        timer.expires_at(timer.expires_at() + boost::posix_time::seconds(1));
        timer.async_wait(tick);
    };
    
    timer.async_wait(tick);

    io.run();

    return 0;
    
}