我想启动一个线程,调用的是类的成员方法(非静态方法)。
用boost::bind可以么?类似下面这样:AfxBeginThread(boost::bind(&CTransmitServerDlg::CloseServer, this), this);编译通不过,而且AfxBeginThread好像需要传递一个 UINT (*)(void) 函数指针,这里应该怎么写?
用boost::bind可以么?类似下面这样:AfxBeginThread(boost::bind(&CTransmitServerDlg::CloseServer, this), this);编译通不过,而且AfxBeginThread好像需要传递一个 UINT (*)(void) 函数指针,这里应该怎么写?
{
protected:
string name_;
public:
myclass()
: name_("hello world")
{
}
void work()
{
for(int i=0;i<100;i++)
{
cout << name_ << endl;
Sleep(10);
}
}
}
int main()
{
myclass c;
boost::thread thd(boost::bind(&myclass::work,&c));
thd.join();
}
UINT MyControllingFunction( LPVOID pParam );
boost::bind(&CTransmitServerDlg::CloseServer, this)boost::bind应该可以通过传递给它的this参数,构造一个普通函数的指针以供调用吧?不然还要它做什么?
class CYourClass
{
public:
CYourClass();
virtual ~CYourClass();protected:
static DWORD WINAPI ThreadProc(LPVOID lpParam);
void DoSomething();
}
DWORD CYourClass::ThreadProc(LPVOID lpParam)
{
CYourClass* pThis = (CYourClass*)lpParam;
pThis->DoSomething();
return 0;
}
C++里面线程启动函数不支持this指针得传递吧;
如果是C#得话,还可以去实现。
似乎应该转化为,
1.在线程启动前设置相关参数;
2.线程根据设置得不同,执行不同得操作。这样,只有一个threadproc就可以了。
只是要bind的时候要提供合适生存期的对象。
你可以去boost.org论坛问问,或者自己看看bind.hpp原理,更或者,你自己改bind.hpp,把你想要的东西暴露出来
但是我并不推荐这么做
http://www.vckbase.com/document/viewdoc/?id=1817
#include "stdafx.h"
#include "windows.h"
#include "stdio.h"class CObject
{
public:
CObject(int a){ m_nData = a;};
DWORD WINAPI ThreadFuc()
{
printf("Thread Run\nThread Data:%d \n", m_nData);
return 0;
};
private:
int m_nData;
};
typedef DWORD ( CObject::*MyThread)(LPVOID lpThreadParameter);int main(int argc, char* argv[])
{
MyThread My = (MyThread)&CObject::ThreadFuc;
CObject b(10);
HANDLE hThread = ::CreateThread(NULL, NULL, *(LPTHREAD_START_ROUTINE*)&My, &b, NULL, NULL);
system("pause");
::CloseHandle(hThread);
return 0;
}