Previous | Next --- Slide 3 of 24
Back to Lecture Thumbnails
sfackler

C++'s classes offer a safer way of dealing with remembering to unlock the mutex. For example, Boost provides the boost::scoped_lock template. It's a class which wraps a mutex. Its constructor locks the mutex and its destructor unlocks the mutex. This guarantees that the mutex will end up being unlocked when we leave the function, whether that be by returning or even throwing an exception:

void insert(List *list, int value) {
    boost::scoped_lock<boost::mutex> lock(list->lock);

    ... Rest of the code, with no explicit unlocks ...
}

The lock variable goes out of scope when the function returns (or an exception causes the stack to unwind past this function call), causing its destructor to be called which unlocks the lock.

mschervi

Note from @thedrick in class: The second unlock in the delete function should be outside of the while loop.

Thedrick

Protecting the entire linked list with one lock does not do well for parallelism. By locking the list, you are unable to add or delete anything from it in another thread. This approach would work pretty well if a lot of your operations are read-only, but with a high number of write operations, this would probably be slower than a serial version with the overhead of locks.

markwongsk

@sfackler: is this like a synchronized in Java?

rutwikparikh

We can do much better than using one lock but locking individual elements of the linked list based on the dependencies for insert/delete. This will allow us to ensure parallelism for these operations while avoiding data corruption..