Quantcast
Channel: CodeGuru Forums - Visual C++ Programming
Viewing all articles
Browse latest Browse all 3027

Can local variable be passed as parameter into a new thread?

$
0
0
Can local variable be passed as the parameter for a new created thread procedure? Here is the example code:

Code:

void CDLG::some_function()
{
        CString strFileName="abc.doc";
        //local variable, can it be valid for being passed into the following new thread???       
        //Can strFileName still be accessed from within the stack of thread procedure?
        ::AfxBeginThread(ProcessContentThread,(LPVOID)&strFileName);
}

UINT ProcessContentThread(LPVOID p)
{
        CString* pstr=(CString*)p
        CString strFile=*pstr;
        //process the file
        ...

}

There is another method using variable on the heap,

Code:

void CDLG::some_function()
{
        CString strFileName="abc.doc"; 
        CString* pstrFN=new CString(strFileName);       
        ::AfxBeginThread(ProcessContentThread,(LPVOID)pstrFN);
}

UINT ProcessContentThread(LPVOID p)
{
        CString* pstr=(CString*)p
        CString strFile=*pstr;
        delete pstr;
        //process the file
        ...

}

I test these code, both methods work as expected, but I doubt whether the first method is a good way. OR if only the second method is the correct way to pass a parameter to a thread. Thank you for help!

Viewing all articles
Browse latest Browse all 3027

Trending Articles