Boost logo

Boost Users :

From: Raul Huertas Diaz (rhuertas_at_[hidden])
Date: 2002-09-06 05:18:20


El Thu, 5 Sep 2002 23:34:39 +0200
Luis De la Parra <lparrab_at_[hidden]> escribió:

>
> hi all,
> is there a way to get a reference to the function object used by a
> boost::thread object??
> when you create a new thread and feed it a function object it copies it and
> then starts a new thread of execution on this object.. well, I would like to
> send messages to the object in which the thread is running but I don't know
> how to do it with boos.threads...
>

I use the pimpl idiom with a boost::shared_ptr<> doing the trick.

It's not very clean, but here goes my example:
---------------------------------------------------------
#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <iostream>
#include <boost/shared_ptr.hpp>

class counter_thread
{
  public:
    counter_thread(): _pimpl(new counter_thread_impl) {}
    void Print() { _pimpl->Print(); }
    void Incr() { _pimpl->Incr(); }
    void operator()() { _pimpl->Run(); }
  
  private:
    class counter_thread_impl
    {
      public:
        counter_thread_impl() : _counter(0) { }

        void Run()
        {
            for(unsigned i=0; i<10;++i) {
                Print();
                Incr();
                boost::xtime xt;
                boost::xtime_get(&xt, boost::TIME_UTC);
                xt.sec += 1;

                boost::thread::sleep(xt);
            }
        }

        void Print()
        {
            boost::recursive_mutex::scoped_lock block_now(mutex);
            std::cout << "Counter: " << _counter << std::endl;
        }
        void Incr()
        {
            boost::recursive_mutex::scoped_lock block_now(mutex);
            ++_counter;
        }

      private:
        unsigned _counter;
        boost::recursive_mutex mutex;
    };

    boost::shared_ptr<counter_thread_impl> _pimpl;
};

int main(int argc, char* argv[])
{
    counter_thread theCounter;
    boost::thread threadManager(theCounter);
    for(unsigned i=0; i<10;++i) {
        theCounter.Print();
        boost::xtime xt;
        boost::xtime_get(&xt, boost::TIME_UTC);
        xt.sec += 1;

        boost::thread::sleep(xt);
    }
    threadManager.join();
}
---------------------------------------------------------

Note that, in main(), theCounter.Print() prints the correct value.

Hope it helps.

-- 
Raúl Huertas Díaz
Redes y Comunicaciones
Ingeniero de Sistemas
TCP Sistemas e Ingenieria
Fernández Caro, 7, 3ª planta
Tel.: +34 91 367 32 79 (Ext. 535)
Fax:  +34 91 407 71 39
rhuertas_at_[hidden]
http://www.tcpsi.es

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net