Re: thread safe
sagenaut@yahoo.com <sagenaut@gmail.com> wrote:
I have a monitor like class and a thread-safe queue:
First of all, C++ doesn't specify threats and mutexes and
the like, and thus your question goes possibly to
the wrong forum. How mutuxes perform is up to the underlying
operating system providing such services. Let's assume POSIX
for the time being.
However:
void put()
{
putLock_.lock();
queue_.push(item);
emptyLock_.signal();
putLock_.unlock();
}
void get()
{
getLock_.lock();
while (queue_.empty()) emptyLock_.wait();
item = queue_.front();
queue_.pop();
getLock_.unlock();
}
Are the put() and get() thread safe?
No, unless the queue has some synchronization handling of its own.
A thread running into get() might preempt any time by a thread running into
put, thus the state seen within get() need not to be consistent. There should
be exactly one access mutex to the thread that is used by both using get()
and put(). However, you *cannot* hold that mutex within the wait loop of
get() as this will cause the getter to block the access, and thus prevents
any thread to run into put(). Thus, this would be essentially a deadlock.
You should first wait for the emptyLock, then try to get access to the
queue, then try to remove an element. Concerning emptyLock: This *should not*
be a mutex at least for the operating systems I know. Locking a mutex within
one thread and releasing it in another is at least undefined within POSIX
(and of course undefined within C++ which has no say about threads and
mutexes in first place), so a semaphore would be the way to go.
void put()
{
serializeLock_.lock();
queue_.push(item);
serializeLock_.signal();
serializeLock_.unlock();
}
void get()
{
serializeLock_.lock();
while (queue_.empty()) serializeLock_.wait();
item = queue_.front();
queue_.pop();
serializeLock_.unlock();
}
That's broken, too. See above.
Which is the right way to implemt the put() and get()? Thanks in
advance.
None of the above. (-: See the comments.
So long,
Thomas
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]