Boost logo

Boost Users :

Subject: Re: [Boost-users] [Newbie] How to create a class member thread
From: vicente.botet (vicente.botet_at_[hidden])
Date: 2009-02-24 17:03:22


----- Original Message -----
From: "Daniele Barzotti" <daniele.barzotti_at_[hidden]>
To: <boost-users_at_[hidden]>
Sent: Tuesday, February 24, 2009 6:35 PM
Subject: [Boost-users] [Newbie] How to create a class member thread

>
> Hi,
>
> I'm sure the question is very banal...
>
> I have a thread object stored in a class:
>
> class MyClass {
>
> private:
> void Init();
> boost::thread _thread;
> }
>
> How can I create it in the implementation code?
>
> MyClass::Init()
> {
> // start thread here...
> }

Hi,

You can not. Thread is default constructible but not copy constructible.

You can do

MyClass() : _thread(fct) {}

If you want to start the thread later on you need a pointer to a thread

class MyClass {
 
private:
    void Init();
    scoped_ptr<boost::thread> _thread;
}

MyClass() : _thread(0) {}
MyClass::Init() {
    _thread.reset(new boost::thread(fct));
    ....
}

If you can not have a pointer, you can use a volatile boolean as follows:

voif fct(volatile bool& started) {
    while(!started) ;
    // start here the real function
}

MyClass() : _started(false), _thread(bind(fct, _started)) {}
MyClass::Init() {
    _started=true;
    ....
}

BTW, why do you want to start the thread on the Init function and not on the constructor?

HTH,

Vicente


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