2
\$\begingroup\$

If I have a data structure for the Allegro threading API as shown in the example here:

https://wiki.allegro.cc/index.php?title=Allegro_5_Tutorial/Threads

And I lock the mutex, is there a way to have one of the members of that data structure be a reference to an entire object that has read/write access to its public member functions locked?

That is to say, if I have a member variable which is a reference to a non POD-type object in that data structure, will locking the mutex restrict access to all of the object's members in another thread, or will it simply lock the reference itself from being modified?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Regardless of the use of Allegro, a mutex and threading is a set of agreements made between yourself, and the rest of your code to enforce "MUTual EXclusion" of the use of shared data.

Simply locking a mutex doesn't ensure the data will not be touched. It's not the data itself that's locked, it's the thread the mutex is running on.

What is necessary with the use of a mutex is to ensure your code only touches the shared data when a lock is actually acquired. This means hands off when you don't have a lock on the resource!

So to answer your question, it's not the struct the mutex is wrapped in, it's the data you mark as off limits to threads that don't have a lock. The actual enforcement is entirely optional, and up to you.

Thread 1

LockMutex(m);
my_vector.resize(my_vector.size()*2);
UnLockMutex(m);

Thread 2

LockMutex(m);
process_vector(&my_vector);
UnlockMutex(m);

Now no matter which thread is running, only one will be allowed to access my_vector at a time.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .