Search code examples
c++boostboost-asioboost-thread

How can I start a boost Thread running a class function?


im doing a C++ class where, internally, i want to create a thread to execute a function of the class, how can I do this? I show you some code.

Member function i want to run in a thread:

void SocketServer::runServer(){
    bool connected;
    tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), puerto));
    std::string data;

    while(seguirFuncionando()){
        miSocket = new tcp::socket(io_service);
        std::cout << "Waiting for connection...\n";
        a.accept(*miSocket);
        std::cout << "Connected\n";
        connected = true;
        try{
            while (connected){
                data = readStr();
                if (data.compare("")==0){
                    std::cout << "End of connection.\n";
                }
                else{
                    std::cout << data << "\n";
                }
            }
        }
        catch (std::exception& e){
        std::cerr << "Exception in thread: " << e.what() << "\n";
        }
    }
}

What im trying to do:

void SocketServer::runThreadServer(){
    asio::thread t(runServer);
}

But it doesnt compile. Error:

no matching function for call to 'asio::thread::thread() note: candidates are: asio::thread::thread(Function) [with Function = void (SocketServer::*)()]

How should i do this?

Thanx.


Solution

  • Like Joachim Pileborg said, the standard way to do this is to use boost::bind. boost::bind specifically makes a construct named boost::function (which may be passed in the c'tor of boost::thread) from a C++ object and its member function.

    Something like this:

    boost::thread t(boost::bind(&SocketServer::runServer, this));