Re: Locking an STL-like container
- From: "Earl Purple" <earlpurple@xxxxxxxxx>
- Date: 9 Jun 2006 02:21:58 -0700
Christian Rössel wrote:
I have an STL-like container, i.e. it provides iterators by
begin() and end() methods and has some insert() and erase()
functionality (and more).
For locking the container while insert() and erase() methods are
executed I considered using scoped locks from the loki library.
That's easy.
But limited, as you said they do not support read-write locks.
But how can I prevent the scenario that one thread calls erase()
or insert() (which may invalidate iterators) while another thread
iterates over the container?
Your reader thread must take a snapshot then release the lock. Normally
you will have a class that "has" your container and controls locking.
You lock, read as much as you need from the collection to contain
something your function can work with, then unlock. Only lock during
the whole process if there is not going to be much processing outside.
My first idea was to add a public
method so that a user of the container can lock the modifying
methods "from outside" for the duration of his operation while
allowing concurrent "read"-operations. I assume that this can be
done using some read_write_mutex.
Better that your class does all the locking when it needs to. Also,
keep read-only methods const, even though you technically modify the
state of the class by locking its read-write-mutex. This can either be
done by making the read-write mutex mutable, or the sneaky workaround
of having a pointer to the mutex. (Can even be boost::scoped_ptr, and
can be std::auto_ptr if you are careful). I prefer mutable myself.
But my actual question is if this is a reasonable approach. Since
I'm new to multithreading I appreciate every illuminating comment.
We are just in the process of moving our application into a
multithreaded environment, so providing a policy is a good point.
Thanks. (With the Loki-Locks you can switch between single- and
multi-threaded using defines, but they provide no read-write locks.)
I don't use Loki but I don't like using defines for this kind of thing.
If you really have to have two policies, use a template. (I have my own
shared pointer that has a thread-safety and a non-thread-safety policy
with regard to its reference count. The non-thread-safe one can be used
even in a MT environment most of the time).
It's simple enough to write your own RAII read-write lock class based
on pthread_rwlock (API).
.
- Prev by Date: Re: Communication between threads from different processes
- Next by Date: Re: Communication between threads from different processes
- Previous by thread: static method no locks
- Next by thread: How to implement thread-safe linked lists?
- Index(es):
Relevant Pages
|
Loading