Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi..

Am working on Threads but am slightly confused on the issue how to return the values from the thread function ?? Before am creating a thread function like this:

C++
DWORD WINAPI Thread_Func( LPVOID lpParam )
{
  //Do some stuff...

  return 0;
}


C++
void CMyThreadDlg:: OnBnClickedThread()
{
 int Data_Of_Thread_1 = 1;
 HANDLE Handle_Of_Thread_1 = 0;
 Handle_Of_Thread_1 = CreateThread( NULL, 0,Thread_Func, &Data_Of_Thread_1,0,NULL);  
 if ( Handle_Of_Thread_1 == NULL)
 ExitProcess(Data_Of_Thread_1);
 WaitForSingleObject(Handle_Of_Thread_1,INFINITE);
 CloseHandle(Handle_Of_Thread_1);
}


But Am not getting How to pass parameters to Thread_Func & return the values from Thread_Func.. I mean it looks some what like this:

C++
void Thread_Func(CString csFilePath,  CString &csText)
{
  //Do some stuff with csText...
}

void CMyThreadDlg:: OnBnClickedThread()
{
  // Here after executing the thread, i need the value of csText.
  // csText value is used in some other functions.
}


Can anyone tell me How do i accomplish this task..

Thank you all..
Posted

1 solution

After the WaitForSingleObject() call, you can get the value "returned" by the thread by using GetExitCodeThread()[^]

Additional Info: I see that you also asked about sending parameters to the thread. The easiest method is to pass a single parameter that is a pointer to a structure (struct) that contains the multiple pieces of data you want to send. You already have the basic form for doing that in the code you posted.

Also, looking at your example, I see that you simply create the thread and then wait for it to finish before proceeding. I hope this is just the example for your learning as it is really a bad use of threads. If all you do is create the thread and immediately wait for it to terminate, you are getting no benefit from threads at all as you are serializing the execution of the code. So you have all the overhead of creating the argument list and figuring out how to get the return value and no benefits over a simple direct call to a function.
 
Share this answer
 
v2
Comments
Guru_C++ 3-Oct-12 9:42am    
Thanks Chuck .. Really i have no idea about the threads am beginner in that.. Please suggest me How do i Properly create a thread & Terminate it..
Chuck O'Toole 3-Oct-12 10:35am    
Search CodeProject for threads, there are many fine articles here that will help you get started. Also, Google for learning threads and you should find lots of "getting started" articles.
Guru_C++ 4-Oct-12 0:39am    
Thank you Chuck :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900