我想启动一个线程,调用的是类的成员方法(非静态方法)。
用boost::bind可以么?类似下面这样:AfxBeginThread(boost::bind(&CTransmitServerDlg::CloseServer, this), this);编译通不过,而且AfxBeginThread好像需要传递一个 UINT (*)(void) 函数指针,这里应该怎么写?

解决方案 »

  1.   

    第一个参数需强制转(void*)
      

  2.   

    boost::bind是和boost::thread结合的class myclass
    {
    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();
    }
      

  3.   

    不行吧,类的成员函数如果不是静态的不能作为线程的启动函数,另外线程启动函数的声明是固定的,如下:
    UINT MyControllingFunction( LPVOID pParam );
      

  4.   

    boost::bind或者boost::mem_fn不能把成员函数指针转换成普通指针吗?不行吗?
      

  5.   

    非静态成员函数指针永远不能转换到普通函数指针,编译器不允许,因为this参数的关系
      

  6.   


    boost::bind(&CTransmitServerDlg::CloseServer, this)boost::bind应该可以通过传递给它的this参数,构造一个普通函数的指针以供调用吧?不然还要它做什么?
      

  7.   


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

  8.   

    boost没用过。
    C++里面线程启动函数不支持this指针得传递吧;
    如果是C#得话,还可以去实现。
      

  9.   

    线程不是越多越好,按照你的说法“为每个需要作为新线程运行的成员函数写一个普通函数”
    似乎应该转化为,
    1.在线程启动前设置相关参数;
    2.线程根据设置得不同,执行不同得操作。这样,只有一个threadproc就可以了。
      

  10.   

    二楼已经提供解决方案,function是一个对象,并没提供转换成普通函数,即使能转,也因为this指针而无法访问成员。
      

  11.   

    boost的bind可以是普通成员函数。
    只是要bind的时候要提供合适生存期的对象。
      

  12.   

    boost::bind(&CTransmitServerDlg::CloseServer, this);我这里给它传了对象的引用/指针,为什么还不能把成员函数给我转换成普通函数,那它拿这个this干什么去了?
      

  13.   

    boost:bind是给用boost写程序的程序员用的东西,实在你要这么用
    你可以去boost.org论坛问问,或者自己看看bind.hpp原理,更或者,你自己改bind.hpp,把你想要的东西暴露出来
      

  14.   

    例如boost::thread.hpp是对thread的封装,默认的threadID是私有的,这是为了安全的目的,我见过有人就自己改boost代码,把threadID给暴露出来了,
    但是我并不推荐这么做
      

  15.   

    用boost::bind加boost::thread可以做到
      

  16.   

    用Thunk技术可以,不过比较复杂。
    http://www.vckbase.com/document/viewdoc/?id=1817
      

  17.   

    这儿有个简单的方法:
    #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;
    }