[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... } Tnx. Daniele.
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... }
This way thread object is created by default contructor. You probably wanted something like this: void threadFunc(); MyClass::MyClass() : _thread(&threadFunc) {}; Or: class MyClass { private: void Init() { _thread.reset(new boost::thread(&threadFunc)); } boost::shared_ptrboost::thread _thread; };
----- Original Message -----
From: "Daniele Barzotti"
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_ptrboost::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
vicente.botet ha scritto:
BTW, why do you want to start the thread on the Init function and not on the constructor?
Hi, first, thanks a lot for the suggestion! The Init function was an example. My real class is a RS232 wrapper. I have to start a thread to continuous reading from ports, but only when the user call the open() method. I need the thread has a class scope because in the close() method where I close the thread and I call thread.join() void SerialPort::reading() { while (!_stoprequested) { reading.... } } bool SerialPort::open(void) { try { _thread.reset(new boost::thread( boost::bind(&SerialPort::reading, this)); } catch (boost::thread_resource_error e) { // Failed to create the new thread return false; } } bool SerialPort::close(void) { if (m_serial_port.IsOpen()){ // If the port is open, then the reading thread is _stoprequested = true; try{ _thread.join(); } catch (boost::thread_interrupted e) { //The thread is already stopped..do nothing } m_serial_port.Close(); } return true; }; So I think the pointer solution is good! Thanks again. Daniele.
participants (3)
-
Daniele Barzotti
-
Igor R
-
vicente.botet