从线程调用类成员函数 [英] Call a class member function from a thread

查看:214
本文介绍了从线程调用类成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这有效,但界面冻结,直到功能完成

  void  CJewelDoc :: OnBstart( )
{
// TODO:在此处添加命令处理程序代码
m_Model.Solver();
}







这个编译但是函数没有调用,界面冻结它似乎线程挂起



  void  CJewelDoc :: OnBstart()
{
// TODO:在此处添加命令处理程序代码
std :: thread t(& CModel :: Solver,& m_Model);
t。 join ();
}

解决方案

在第一种情况下,接口冻结,因为它是执行求解器函数并且它不再处理消息队列,只要在解算器函数内部没有getMessage并且没有消息处理例程。



我会在类中声明Solver函数为static,然后使用CreateThread函数启动线程:



在Model.h中

 class CModel 
{
static UINT Solver(LPVOID pParam);
}





在Model.cpp中

 UINT CModel ::求解器(LPVOID pParam)
{
//无论你想在这个函数中做什么,
返回0;
}





最后:

 void CJewelDoc :: OnBstart ()
{
// TODO:在这里添加命令处理程序代码
CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)CModel :: Solver,NULL,NULL,NULL);
}





应该与你的第二个解决方案完全相同,但它对我有用而不会冻结界面..


This works but the interface freezes until the function is complete

void CJewelDoc::OnBstart()
{
    // TODO: Add your command handler code here
    m_Model.Solver();
}




this compiles but the function isn't called and the interface freezes it appears the thread hangs

void CJewelDoc::OnBstart()
{
    // TODO: Add your command handler code here
    std::thread t(&CModel::Solver, &m_Model);
    t.join();
}

解决方案

Hi, in the first case, the interface freezes because it is the main thread that is executing the "Solver" function and it is not handling the message queue any more as long as inside the "Solver" function there is no getMessage and no message handling routine.

I would declare the "Solver" function as static inside the class and then start the thread with the CreateThread function:

In Model.h

class CModel
{
    static UINT Solver(LPVOID pParam);
}



In Model.cpp

UINT CModel::Solver(LPVOID pParam)
{
    // Whatever you want to do in this function
    return 0;
}



And finally:

void CJewelDoc::OnBstart()
{
    // TODO: Add your command handler code here
    CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)CModel::Solver, NULL, NULL, NULL);
}



Should be quite the same as your second solution, but it works for me without freezing the interface..


这篇关于从线程调用类成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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