El Thu, 5 Sep 2002 23:34:39 +0200
Luis De la Parra 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
#include
#include
#include
#include <iostream>
#include
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 _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@tcpsi.es
http://www.tcpsi.es