Re: Thread Function and access
"Peter Schmitt" wrote:
I have a written a Thread class (CMyThread) and have a
question
concerning the Thread Safety.
The reason for using a Thread is because i need to check
the Version of
Application (multilanguage) online by downloading the
version string.
Normally this action takes several seconds.
So i decided to call the Run() method of CMyThread, for
example:
Run("Connection failed", "New Version available", "You're
using the
latest Version" ...);
For easy explanation i will use only one string in the
following class.
My question is, if it's safe to access this.m_msg in the
Run Method. Or
is there any way to tell the Thread to call a method of my
CMyThread
after (!) executiuon to display the version check result?!
Thanks for any answers and best regards
class CMyThread
{
private string m_msg;
bool Start(string msg)
{
// Save string for later access in Run Method
this.m_msg = msg;
_beginthreadex(NULL, 0, &Starter, this, 0,
&m_ThreadID);
}
// The one and only Thread Function for performing some
work
unsigned Run()
{
// Is it safe to access this.m_msg here?!
// For example:
MessageBox(NULL, this.m_msg.c_str(), "", NULL);
// or...
this.m_msg = "some text";
// ...
return 0;
}
static unsigned __stdcall Starter(void* pVoid)
{
CMyThread *pInst = (CMyThread*)pVoid;
unsigned iRet = pInst->Run();
_endthreadex(iRet);
^^^^^^^^^^^^^^^^^^
No need to call `_endthreadex'. It will be called
automatically by `_beginthreadex' when thread function
returns.
return iRet;
}
};
Actually, from the code you posted it's hard to tell whether
`CMyThread' class is thread safe. The most important part is
to keep `m_msg' member intact while thread is running. For
example, this usage won't be thread safe and likely will
lead to crash:
<code>
bool Foo()
{
CMyThread myThread;
bool ret = myThread.Start("Hello");
return ret;
}
</code>
Here, `CMyThread' instance is created, new thread is started
and then function exits. So, local variable `myThread' is
destroyed upon return from `Foo' while new thread can be
still running. Any access to `m_msg' or even `this' within
the thread will cause an access violation, if you're lucky,
or will silently corrupt memory.
HTH
Alex