domlao
domlao

Reputation: 16029

Prevent Other Thread To Read Resources

How can I prevent the other thread to access or read the resource of an object? Like for example in a method I want to lock that method while a method call accessing the resource of the object so that the other thread when they call that method it will not access the resource of the instance while the first thread accessing it?

Like for example,

int CFoo::FooReadData( int tag )
{
    std::map<int, int>::const_iterator iter = resource.find(tag);

    return *iter.second;
}

In the above method, I want to prevent other calling thread to access the "resource" while other thread accessing it.

Thanks.

Upvotes: 0

Views: 109

Answers (1)

MRB
MRB

Reputation: 3822

You can use ThreadSafe data structures like Intel TBB.

but in your example:

define a mutex:

std::mutex m;

int CFoo::FooReadData( int tag )
{
    std::lock_guard(m);

    std::map<int, int>::const_iterator iter = resource.find(tag);

    return *iter.second;
}

(However you need a c++11 compiler to use data types such as std::mutex)

Upvotes: 2

Related Questions