essay on programming languages, computer science, information techonlogies and all.

Wednesday, June 21, 2023

C++ catches

Can you find a catch at the code below ? Occasionally I see "loop starting ..." then "loop end ..." but no "loop ... ".

class ScopeFeeder
{
public:
    ScopeFeeder() : 
        loop_thread__( [this](){ loop(); } )
    {}

    ~ScopeFeeder()
    {
        stop_ = true;
        loop_thread__.join();
    }
...

private:
    std::thread loop_thread__;
    bool stop_ = false;

    void loop() 
    {
        cout << "loop starting ...\n";
        while( !stop_ )
        {
            cout << "loop ...\n";
...
        }
        cout << "loop end ...\n";
    }
};
s

c

r

o

l

l



d

o

w

n



stop_ can be true when loop() is running obviously. And it can be as initilizaton order matters in here and stop_ has to be initialized first. If you put stop_ in front of loop_thread_, then stop_ is not undefined anymore and loop() will run happily ever after.

class ScopeFeeder
{
...

private:
    bool stop_ = false;              // stop_ first.
    std::thread loop_thread__;

...
};