dimanche 15 novembre 2020

Threaded member function getting wrong value from member variable

This should a simple code, but it's not working properly.
The member function, running as a thread, is getting the wrong value from the member variable.

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



class Worker
{
    private:
        const int workerID;
        
        
    public:
        Worker( int id ) : workerID( id )
        {
            std::cout << "Constructor: " << workerID << std::endl;
            std::this_thread::sleep_for( std::chrono::milliseconds( 500 ));

            std::thread thread( &Worker::Run, this );
            thread.detach( );
        }
        
        
    private:
        void Run( )
        {
            std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ));
            std::cout << "Worker: " << workerID << std::endl;
        }
};



int main()
{
    std::vector<Worker> workers;
    
    workers.emplace_back( 1 );
    workers.emplace_back( 2 );
    
    std::this_thread::sleep_for( std::chrono::milliseconds( 2000 ));
    return 0;
}

The expected output was:

Constructor: 1
Constructor: 2
Worker: 1
Worker: 2

But instead I am getting:

Constructor: 1
Constructor: 2
Worker: 0
Worker: 2

Could someone enlighten me why it's behaving this way?
What am I doing wrong?
Thanks!

Aucun commentaire:

Enregistrer un commentaire