Click here to Skip to main content
15,918,268 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i wanna write a threading object has a virtual member function ,can override.
C++
#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;
}

in line 18.
C++
virtual void run()

how can i make a threading object.this object can be inherited and the member function can be overrode.
Posted
Updated 2-Jul-13 22:49pm
v2
Comments
vijith.squadz 3-Jul-13 4:54am    
What failure you are getting ? It works fine for me with VS2012

1 solution

The specification of the thread function is not correct. Use

C++
_beginthread (&gangplank, 0, (void *)this);


[AMENDED]
In addition, you should wait in the destructor of your thread until the newly created workerthread has ended. What happens now is that in main you create a "d" object, call its start() function, and then terminate main. This will destroy the "d" object, even before the thread had a chance to run. Then, when the thread's worker function is finally called, the "d" object has already been destroyed, and hence its v-table is invalid. But this v-table is needed to call a virtual function. This is also the reason why your example runs without declaring the run function as virtual. In that case the v-table is not needed and it doesn't matter that the "d" object is already gone.

As a simple test, put a Sleep (1000) before the call of _endthread. Eventually you will need a more sophisticated thread termination sequence.

[AMENDED-2]
And there is one more problem in your code: _endthread must be called from the thread that you want to terminate. Instead it is called here from the main thread. That even makes things worse. Your thread function ends anyway after you do "cout << 2". So there is actually no need to call _endthread. If you are going to extend your example to a full application, you want to put _endthread into you run function.
 
Share this answer
 
v3
Comments
Ken Chiayuan Chang 3-Jul-13 5:18am    
it still incorrect~
nv3 3-Jul-13 6:02am    
See my amendments above.
[no name] 3-Jul-13 21:20pm    
If this solved your problem then it is polite to accept the solution. My 5 anyway.
nv3 4-Jul-13 2:15am    
Thank you!
zlogdan 4-Jul-13 2:16am    
Agreed! My 5 stars answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900