dimanche 29 novembre 2015

Destructor called before end of scope

The following program chrashes. But I don't really understand why. The boolean my_shared_resouce is in real life an asynchonous queue that eventually stops the loop inside of the thread via message passing. However, the following program crashes because the destructor seems to be called multiple times. And the first time it does is long before the sleep in the main() finishes. If i remove the delete my_shared_resource; I can see the destructor is called three times... However, following my current understanding the destructor should only be called when main() finishes.

#include <thread>
#include <chrono>
#include <iostream>

using namespace std;

class ThreadedClass {

    public:

        ThreadedClass() {
            my_shared_resource = new bool(true);
        }

        virtual ~ThreadedClass() {
            delete my_shared_resource;
            cout << "destructor" << endl;
        }


        void operator()(){
            loop();
        }

        void stop() {
            *my_shared_resource = false;
        }

    private:

        void loop() {
            while (*my_shared_resource) {
                // do some work
                this_thread::sleep_for(std::chrono::milliseconds(1000));
            }
        }

        bool* my_shared_resource;
};

int main(int argc, char** argv) {

    ThreadedClass instance;
    std::thread t(instance);
    this_thread::sleep_for(std::chrono::milliseconds(1000));
    cout << "Did some work in main thread." << endl;
    instance.stop();
    t.join();
    return 0;
}

compiled with g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4

compiled as g++ --std=c++0x thread.cpp -pthread

Would someone please enlighten me what is wrong about this design.

Aucun commentaire:

Enregistrer un commentaire