CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13

Threaded View

  1. #1
    Join Date
    Jan 2003
    Posts
    375

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

    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!
    Last edited by forester; April 1st, 2013 at 04:20 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured