Re: Handling access to shared resources
On May 10, 7:03 pm, Jerry Coffin <jcof...@taeus.com> wrote:
In article <f477a125-df51-43e0-86d0-
4ebbb3457...@s31g2000vbp.googlegroups.com>,
anguscom...@gmail.com says...
I am having a problem with access to a shared std::list.
The list is accessed via different threads and I use a mutex
lock/unlock to ensure that only one process can work on the
list at any one time. The trouble is the lock and unlock is
scattered through the code. I am having problems where I do
a lock but there is no unlock and the code gets stuck. It
is quite tricky to debug of course.
Does anyone have any tips on how to handle this problem.
Should I use some global/singleton accessor function to
access the list? But I do need to perhaps edit/delete/add
to the list. so how best to handle?
Write a class that supports the actual operations you care
about, and implement the atomicity inside of those individual
operations. At least for adding and deleting, this can be
pretty simple:
class storage {
std::list<whatever> list;
MUTEX m;
public:
void add(whatever const &a) {
acquire(m);
list.insert(a);
}
void delete(whatever const &a) {
acquire(m);
std::list<whatever>::iterator pos;
pos = list.find(a);
list.remove(pos);
}
};
I suspect that this example is incomplete. It's not clear what
"acquire(m)" does, but if it simply acquires the lock (as it's
name suggests), then you're missing the releases. And of
course, since you can also exit the sequence because of an
exception (at least in the case of add), you have to ensure that
it is called then as well---the classical scoped lock pattern
should definitely be used.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34