I have the following class which kicks off a new std::thread. I now want the thread to access a member variable of the class. So far I cannot work out how to do this. In my MyThread function I want to check m_Continue.
I have tried passing in 'this' when the thread is created but I get an error:
Error 1 error C2197: 'void (__cdecl *)(void)' : too many arguments for call c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional 1152 1 MyProject.
class SingletonClass
{
public:
SingletonClass();
virtual ~SingletonClass(){};
static SingletonClass& Instance();
void DoSomething();
private:
static void MyThread();
std::thread* m_Thread;
bool m_Continue;
};
SingletonClass::SingletonClass()
{
m_Continue = true;
m_Thread= new std::thread(MyThread, this);
}
void SingletonClass::MyThread()
{
while(this->m_Continue )
{
// do something
}
}
void SingletonClass::DoSomething()
{
m_Continue = false;
}
SingletonClass& SingletonClass::Instance()
{
static SingletonClass _instance;
return _instance;
}
int _tmain(int argc, _TCHAR* argv[])
{
SingletonClass& singleton = SingletonClass::Instance();
singleton.DoSomething();
return 0;
}
How can I do this??
m_thread
could simply be astd::thread
that you assign:m_thread = std::thread{MyThread, this};
. Also, your program has undefined behavior due to a data race onSingletonClass::m_Continue
since it can potentially be accessed in the spawned thread while simultaneously being modified in the main thread. You need to either make it astd::atomic<bool>
or protect accesses to it with astd::mutex
. – Casey