But the question now is, m_pThread=new STD: : thread (STD: : bind (& amp; CThread: : run, this)); Then thread execution, always call the CThread the run function, such as in the following MyThread run function call is less than all the time,
Like the following test code
STD: : function
Can call to run function of MyThread, why to STD: : thread will not be able to dynamically bound?
How to solve this??
class CThread
{
Public:
CThread ()
{
}
Virtual ~ CThread ()
{
If (m_pThread)
{
If (m_pThread - & gt; Joinable ())
{
M_pThread - & gt; The join ();
}
The delete m_pThread;
M_pThread=nullptr;
}
}
Void the start ()
{
If (m_pThread)
{
return;
}
//m_pThread=new STD: : thread (& amp; CThread: : run, this);
M_pThread=new STD: : thread (STD: : bind (& amp; CThread: : run, this));
////-- - test
STD: : functionTestfunc ();
///
}
Void waitForDone ()
{
if (! M_pThread)
{
return;
}
If (m_pThread - & gt; Joinable ())
{
M_pThread - & gt; The join ();
}
}
Void detachThread ()
{
if (! M_pThread)
{
return;
}
If (m_pThread - & gt; Joinable ())
{
M_pThread - & gt; Detach ();
}
}
Protected:
Virtual void the run ()
{
STD: : cout & lt; <"CThread Is Running;
}
Private:
STD: : thread * m_pThread {nullptr};
};
///implementation CThread interface
The class MyThread: public CThread
{
Public:
Protected:
Virtual void the run () override
{
STD: : cout & lt; <"MyThread Is Running.";
}
};
Int main ()
{
MyThread t;
t.start();
T.w aitForDone ();
}
CodePudding user response:
What do you use the compiler? I run on vs2015 results output is run in MyThread, if there is a problem, you can add a layer of indirect invocation address:class CThread
{
Public:
CThread ()
{
}
Virtual ~ CThread ()
{
If (m_pThread)
{
If (m_pThread - & gt; Joinable ())
{
M_pThread - & gt; The join ();
}
The delete m_pThread;
M_pThread=nullptr;
}
}
Void the start ()
{
If (m_pThread)
{
return;
}
M_pThread=new STD: : thread (& amp; CThread: : runWrapper, this);
}
Void waitForDone ()
{
if (! M_pThread)
{
return;
}
If (m_pThread - & gt; Joinable ())
{
M_pThread - & gt; The join ();
}
}
Void detachThread ()
{
if (! M_pThread)
{
return;
}
If (m_pThread - & gt; Joinable ())
{
M_pThread - & gt; Detach ();
}
}
Protected:
Virtual void the run ()
{
STD: : cout & lt; <"CThread Is Running;
}
Private:
Void runWrapper ()
{
The run ();
}
Private:
STD: : thread * m_pThread {nullptr};
};
CodePudding user response: