I think I figured out a better way, which is C++03 compliant using std::enable_shared_from_this. It eliminates the need for std::atomic<bool> m_Quit by using the std::shared_ptr::use_count() instead, which is thread safe.
What do you think?
class ThreadSafeCommunication : public std::enable_shared_from_this<ThreadSafeCommunication>
{
[...]
};
class WorkerThread
{
public:
WorkerThread(DWORD i)
{
spInterface = std::make_shared<ThreadSafeCommunication>(i);
hThread = CreateThread(NULL, 0, WorkerThread::ThreadRoutine, spInterface.get(), NULL, NULL);
}
~WorkerThread(void)
{
if(hThread)
{
CloseHandle(hThread);
}
}
private:
std::shared_ptr<ThreadSafeCommunication> spInterface;
//Thread system
HANDLE hThread;
static DWORD WINAPI ThreadRoutine(LPVOID param)
{
std::shared_ptr<ThreadSafeCommunication> spInterface = static_cast<ThreadSafeCommunication*>(param)->shared_from_this();
while(spInterface.use_count() == 2) //Only 2 strong references, one from main and one from thread.
{
spInterface->TickThread();
//do stuff
}
return 0;
}
};