lundi 31 janvier 2022

Passing shared_ptr in mediator design from one colleague object to other running in different threads

In a mediator design pattern with C++, I need to efficiently pass data from one object (running in one thread) to other object running in another thread using bind() call. Assuming I have a mechanism to enqueue function objects into a thread's execution queue (say Thread->Enqueue( functor ))

//Foo's call -- runs in Thread1's context
void Foo::DoSomeWork()
{
    shared_ptr<Object> o = std::make_shared<Object>()
    //fill the object

    //post to mediator
    M.PostData(o);
}

//Thread1 runs functions for class foo. this is called in Thread1's context
void Mediator::PostData(shared_ptr<Object> data)
{
    //Enqueue the functor into Thread2 execution queue 
    Thread2->Enqueue(std::bind(&Bar::ProcessData, Colleague2.get(), data));
}

//Thread2 context
void Bar::ProcessData(shared_ptr<Object> ReceivedData)
{
    //work on ReceivedData object. runs in Thread2's context
    //data passed on to Bar class
} 

instead of copying the shared ptr in the std::bind, is it possible to do std::move(data) to pass on the shared_ptr

e.g. 
Thread2->Enqueue(std::bind(&Bar::ProcessData, Colleague2.get(), std::move(data)));

Not sure if using unique_ptr<> and try moving twice (one in function, other in std::bind will work or help

Aucun commentaire:

Enregistrer un commentaire