$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
Subject: [Boost-users] [asio] posting a function to an io_service object
From: Vilhelm Sundberg (vilhelmsundberg_at_[hidden])
Date: 2009-12-28 09:14:50
Hi,
I am trying to call a function by posting it to an io_service object
running in a different thread from the main thread of the application.
The problem is the function always gets called from the main thread.
Basically I would like to do this with asio:
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
void f()
{
    cout << boost::this_thread::get_id() << endl;
}
int main(int argc, char *argv[])
{
    cout << "main thread: " << boost::this_thread::get_id() << endl;
    boost::thread t1(f);
    boost::thread t2(f);
    t1.join();
    t2.join();
    return 0;
}
The output is:
main thread: 0x9739628
0x97392e8
0x9739488
Using Boost.Asio, f() always gets called from the main thread:
#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
using namespace std;
using namespace boost::asio;
void f()
{
    cout << boost::this_thread::get_id() << endl;
}
int main(int argc, char *argv[])
{
    io_service ios1;
    io_service ios2;
    io_service::work w1(ios1);
    io_service::work w2(ios2);
    io_service::strand s1(ios1);
    io_service::strand s2(ios2);
    boost::thread t1(boost::bind(&io_service::run, &ios1));
    boost::thread t2(boost::bind(&io_service::run, &ios2));
    cout << "main thread: " << boost::this_thread::get_id() << endl;
    //s1.post(f);
    //s2.post(f);
    ios1.post(s1.wrap(f));
    ios2.post(s2.wrap(f));
    while (ios1.poll() > 0)
        ;
    while (ios2.poll() > 0)
        ;
    ios1.stop();
    ios2.stop();
    t1.join();
    t2.join();
    return 0;
}
The output is:
main thread: 0x9739628
0x9739628
0x9739628
What is the correct way of posting/dispatching a function to an
io_service running in a different thread, so that function is called
from that thread?
Thanks
Vil