dimanche 4 septembre 2016

Efficient multithreading with pointers and methods

I have a question about efficient multithreading when pointers are involved. I have some costly const member function (Foo::DoLotsOfStuff) and want to launch it in another thread (potentially with some other operations) using a lambda function and std::async (see below). The Foo object referred to by this presumably lives on the local thread, so does this mean that I want to pass a copy of the local object to avoid inter-thread communication?

I would imagine this depends on the size of Foo and the costliness of Foo::DoLotsOfStuff, but is there a rule of thumb about whether this should be passed as-is or dereferenced and copied in this kind of situation?

More generally, if dealing with a pointer to an object and wanting to multithread its const methods, is it usually a bad idea to pass the pointer since this can potentially lead to lots of inter-thread communication?

void Foo::Bar() const // version 1
{
   auto fut = std::async(std::launch::async, [this]()
              {
                  //...
                  this->DoLotsOfStuff();
              });
   //...
   fut.wait();
}

void Foo::Bar() const // version 2
{
   Foo copyOfFoo = *this;
   auto fut = std::async(std::launch::async, [copyOfFoo]()
              {
                  //...
                  copyOfFoo.DoLotsOfStuff();
              });
   //...
   fut.wait();
}

Aucun commentaire:

Enregistrer un commentaire