从MFC中的Thread函数返回值 [英] Return the value from Thread function in MFC

查看:139
本文介绍了从MFC中的Thread函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨..

我正在使用线程,但是在如何从线程函数返回值的问题上有些困惑?在创建这样的线程函数之前:

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:

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

  return 0;
}





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);
}



但是我没有得到如何将参数传递给Thread_Func&;从Thread_Func返回值.我的意思是看起来像这样:



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:

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..

推荐答案

调用WaitForSingleObject()之后,您可以使用
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.


这篇关于从MFC中的Thread函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆