Denisof
Denisof

Reputation: 336

Accessing class object from multiple threads

Suppose I have some container class like the one below:

class Container {
public:
    int const & operator[] (int n) const {
        return data[n];
    }
private:
    std::vector<int> data;
}

I need to access its elements from multiple threads, using overloaded operator [] and passing an object of this class to lambda capture by reference:

Container store;
std::thread t_1([&store]() { /* do something here and read from store */ } );
std::thread t_2([&store]() { /* do something here and read from store */ } );

Will there be some slowdowns because of such design? Is it possible to speedup this part somehow?

Upvotes: 3

Views: 398

Answers (1)

Fureeish
Fureeish

Reputation: 13424

Since std::vector's data() lies on the heap anyway, you cannot omit the access there. The only faster way would be to keep the elements on the stacks of the two threads (threads have separate stacks but share heap space), but this is not a possibility here. Thus, I see no optimisations for your case, unless you share your whole implementation and by changing the approach, one may come up with more performant implementation.

I would advise against it, though. That would belong to CodeReview, not StackOverflow.

Lastly, I would like to mention thread safety - I do not see any races here and I believe you specifically made sure that the example does not hint that you may encounter any (by only showing access to reading and not writing to shared resources), but it is still a good idea to check for them. If what you are doing is only reading, no data races will occur.

Upvotes: 2

Related Questions