Re: Thread safe
- From: Joe Seigh <jseigh_01@xxxxxxxxxx>
- Date: Fri, 23 Jun 2006 18:46:30 -0400
sagenaut@xxxxxxxxx wrote:
I have a monitor like class and a thread-safe queue:....
....
Are the put() and get() thread safe? I used two locks for
serialization and one lock for signaling. This allows two threads
access to the queue: one for put and the other for get. Normal
implementation would use only one lock and allows only one thread to
access queue:
Which is the right way to implemt the put() and get()? Thanks in
advance.
You'd probably have to implement it both ways to determine whether it
makes a difference. However, if you use separate mutexes for put and
get, you need to use a common mutex to synchronize memory state, not
just for signaling. Use two queues, one for gets and the other for
puts. Move the entire put queue to the get queue when the latter is
empty.
T * get() {
getLock.lock();
if (queue0.empty() {
putLock.lock();
while (queue0.empty() && queue1.empty()) putLock.wait();
queue0.append(queue1); // append all of queue1 onto queue0
putLock.unlock();
}
T * tmp = queue0.pop();
getLock.unlock;
return tmp;
}
void put(T * item) {
putLock.lock();
if (queue1.empty() putLock.broadcast();
queue1.push(item);
putLock.unlock();
}
Of course if the queues are empty most of the time, this will have
slightly more overhead than using a single lock.
And if lock contention is the problem, this would only cut contention
in half. Lock-free would probably be the better way to qo.
--
Joe Seigh
When you get lemons, you make lemonade.
When you get hardware, you make software. .
- Follow-Ups:
- Re: Thread safe
- From: sagenaut
- Re: Thread safe
- From: Joe Seigh
- Re: Thread safe
- References:
- Thread safe
- From: sagenaut
- Thread safe
- Prev by Date: Re: Thread safe
- Next by Date: Re: pthreads in a cluster
- Previous by thread: Re: Thread safe
- Next by thread: Re: Thread safe
- Index(es):
Relevant Pages
|