jeudi 15 août 2019

Overridden virtual function not called from thread

I am writing a base class to manage threads. The idea is to allow the thread function to be overridden in child class while the base class manages thread life cycle. I ran into a strange behavior which I don't understand - it seems that the virtual function mechanism does not work when the call is made from a thread. To illustrate my problem, I reduced my code to the following:

#include <iostream>
#include <thread>

using namespace std;

struct B
{
    thread t;
    void thread_func_non_virt()
    {
        thread_func();
    }

    virtual void thread_func()
    {
        cout << "B::thread_func\n";
    }

    B(): t(thread(&B::thread_func_non_virt, this)) { }
    void join() { t.join(); }
};

struct C : B
{
    virtual void thread_func() override
    {
        cout << "C::thread_func\n";
    }
};

int main()
{
    C c;   // output is "B::thread_func" but "C::thread_func" is expected
    c.join();
    c.thread_func_non_virt();   // output "C::thread_func" as expected
}

I tried with both Visual studio 2017 and g++ 5.4 (Ubuntu 16) and found the behavior is consistent. Can someone point out where I got wrong?

Aucun commentaire:

Enregistrer un commentaire