1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
Deadlocks can be avoided using the principles described in the previous
section. However, instead of placing the responsibility for avoiding deadlocks
on the shoulders of the software engineer, an alternative approach is
available: a ti(scoped_lock) can be used to lock multiple semaphores at once,
where the tt(scoped_lock) ensures that deadlocks are avoided.
The tt(scoped_lock) also has a default constructor, performing no actions, so
it's up to the software engineer to define tt(scoped_lock) objects with at
least one tt(mutex). Before using tt(scoped_lock) objects the tthi(mutex)
header file must be included. Adapting the example from section
ref(DEADLOCKS): both functions define a tt(scoped_lock) (note that the order
in which the mutexes are specified isn't relevant), and deadlocks are do not
occur:
verbinclude(-ns4 //code examples/lock.cc)
Thus, instead of using tt(lock_guard) objects, tt(scoped_lock) objects can be
used. It's a matter of taste whether tt(lock_guards) or tt(scoped_locks)
should be preferred when only one mutex is used. Maybe tt(scoped_lock) should
be preferred, since it always works....
|