c++ - C++11: std::thread inside a class executing a function member with thread initialisation in the constructor -


i'm trying use std::thread c++11. couldn't find anywhere if possible have std::thread inside class executing 1 of function members. consider example below... in try (below), function run().

i compile gcc-4.4 -std=c++0x flag.

#ifndef runnable_h #define runnable_h  #include <thread>  class runnable {     public:         runnable() : m_stop(false) {m_thread = std::thread(runnable::run,this); }         virtual ~runnable() { stop(); }         void stop() { m_stop = false; m_thread.join(); }     protected:         virtual void run() = 0;         bool m_stop;     private:         std::thread m_thread; };   class mythread : public runnable{ protected:     void run() { while(!m_stop){ /* something... */ }; } };  #endif // runnable_h 

i'm getting error , others: (same error , without $this)

runnable.h|9|error: no matching function call ‘std::thread::thread(<unresolved overloaded function type>, runnable* const)’| 

when passing pointer.

runnable.h|9|error: iso c++ forbids taking address of unqualified or parenthesized non-static member function form pointer member function.  ‘&runnable::run’| 

that approach wrong.

the problem while object still under construction type still not derived type, type of constructor executing. means when start thread object still runnable , call run() can dispatched runnable::run(), pure virtual, , in turn cause undefined behavior.

even worse, might run false sense of security, might case under circumstances thread being started might take long enough current thread complete runnable constructor, , enter mythread object, in case new thread execute correct method, change system execute program (different number of cores, or load of system, or other unrelated circumstance) , program crash in production.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -