C++ Boost Thread

Da Andreabont's Wiki.

Compilare

g++ <file_sorgente> -lboost_system -lboost_thread

Codice

Thread semplice

#include <iostream>
#include <boost/thread.hpp>
#include <boost/lexical_cast.hpp>

int main() {

    boost::thread t([](){
        std::string threadId = boost::lexical_cast<std::string>(boost::this_thread::get_id());
        std::cout << "Thread " << threadId << std::endl;
    });

    t.join();

}

Thread interrompibile

#include <iostream>
#include <boost/thread.hpp>
#include <boost/chrono/chrono_io.hpp>

int main() {
    
    boost::thread t([](){

        std::cout << "Inizio thread" << std::endl;
        
        // Inizio zona critica
        boost::this_thread::disable_interruption di;
        
        // Fine zona critica
        boost::this_thread::restore_interruption ri(di);
            
        // Attendo 10 secondi
        boost::this_thread::sleep_for(boost::chrono::seconds(10));
        
        std::cout << "Fine thread" << std::endl;
        
    });
    
    t.interrupt();
    
    t.join();
    
}