2013-07-03 89 views
0

我想创建一个线程对象,成员函数“run”可以被覆盖。当我添加“虚拟”这个词时,它会失败。有人可以帮助我 - 我如何制作线程对象。该对象可以被继承,并且成员函数可以被覆盖。线程虚拟成员函数

#include <iostream> 
#include <process.h> 
using namespace std; 

class thread 
{ 
private: 
    static void gangplank(void *ptr) 
    { 
     ((thread *)ptr)->run(); 
    } 
public: 
    void start() 
    { 
     _beginthread(&this->gangplank,0,(void *)this); 
     //this->gangplank((void *)this); 
    } 
    virtual void run() 
    { 
     cout<<1; 
    } 
    ~thread() 
    { 
     _endthread(); 
    } 
}; 


class d:public thread 
{ 
public: 
    void run() 
    { 
     cout<<2; 
    } 
}; 

int main() 
{ 
    d a; 
    a.start(); 

    return 0; 
} 

错误消息:

“text.exe已停止工作 - Windows正在检查一个解决问题的办法” 它没有编译错误

+1

当你说“它会运行失败”,你是什么意思?你会得到什么错误? – doctorlove

+0

错误消息是“text.exe已停止工作 - Windows正在检查问题的解决方案” – Ken

回答

0

从析构函数中删除_endthread。

MSDN: 可以调用_endthread或_endthreadex明确终止 线程;但是,当线程从作为参数传递的例程返回到 _beginthread或_beginthreadex时,将自动调用_endthread或_endthreadex 。通过调用endthread或_endthreadex来终止线程有助于确保为线程分配的资源 的正确恢复。

好吧,我现在明白了,_endthread在析构函数中这不是真正的问题,您必须等待主函数中的线程。

#include <process.h> 
#include <iostream> 

using namespace std; 

class thread 
{ 
private: 
    HANDLE m_handle; 
    static void gangplank(void *ptr) 
    { 
     ((thread *)ptr)->run(); 
    } 
public: 
    HANDLE getHandle() const {return m_handle;} 
    void start() 
    { 
     m_handle = (HANDLE)_beginthread(&this->gangplank,0,(void *)this);  
    } 
    virtual void run() 
    { 
     cout<<1; 
    } 
    ~thread() 
    { 
     //_endthread(); 
    } 
}; 


class d:public thread 
{ 
public: 
    void run() 
    { 
     cout<<2; 
    } 
}; 

int main() 
{ 
    d a; 
    a.start(); 
    WaitForSingleObject(a.getHandle(), INFINITE); 
    return 0; 
} 
1

我不知道这是不是你的问题,因为你刚才说这 失败了,没有说怎么样,但是你不等待线程 完成在main,所以你可能会破坏螺纹对象 线程开始运行之前。

0

使用std::thread代替原生C API。它使用函数对象,所以你可能甚至不需要虚函数。如果你的编译器不支持C++ 11,那么你可以使用boost::thread,这几乎是相同的(实际上,它直接使用本地API)。

下面是一个例子:

#include <thread> 
#include <iostream> 

void run() 
{ 
    std::cout << "run" << std::endl; 
} 

int main() 
{ 
    std::thread t(run); 
    t.join(); 
} 

或者你也可以调用类成员:

#include <thread> 
#include <functional> 
#include <iostream> 

class A { 
public: 
void run() 
    { 
     std::cout << "run" << std::endl; 
    } 
}; 

int main() 
{ 
    A a; 
    std::thread t(std::bind(&A::run, &a)); 
    t.join(); 
} 

通常建议如果可能的话,而不是创建一个包装到C使用更高级别的API图书馆自称。 C++标准中的API(通常也用于Boost)通常比一般程序员可以做得更好,并且它肯定比自己实现一个良好的实现节省了大量时间。

+0

非常感谢您全部找到我的解决方案 – Ken