|
Boost Users : |
Subject: [Boost-users] [Thread] Semantics regarding memory barrier/happens-before relationship
From: Falk S. (falk-o-mat_at_[hidden])
Date: 2011-11-08 16:32:26
Hi,
I have read an article on Dr.Dobbs
(http://drdobbs.com/cpp/184401518?pgno=3) about the Boost Thread Library
and a given example quoted below raised a question to me regarding race
condition safety (stripped).
> |const| |int| |BUF_SIZE = 10;|
> |const| |int| |ITERS = 100;|
>
> |boost::mutex io_mutex;|
>
> |class| |buffer|
> |{|
> |public||:|
> | ||typedef| |boost::mutex::scoped_lock|
> | ||scoped_lock; |||
|[..]|
>
> | ||int| |get()|
> | ||{|
> | ||scoped_lock lk(mutex);|
> | ||if| |(full == 0)|
> | ||{|
|[..]|
> | ||while| |(full == 0)|
> | ||cond.wait(lk);|
> | ||}|
> | ||int| |i = buf[c];|
> | ||c = (c+1) % BUF_SIZE;|
> | ||--full;|
> | ||cond.notify_one();|
> | ||return| |i;|
> | ||}|
> | |
> |private||:|
> | ||boost::mutex mutex;|
> | ||boost::condition cond;|
> | ||unsigned ||int| |p, c, full;|
> | ||int| |buf[BUF_SIZE];|
> |};|
I wonder if it is possible the compiler produces optimised code and
checking the member 'full' before creating the scoped lock. Imagine two
threads calling/entering method buffer.get. That would lead to a
possible race condition. Why is this not possible and how is this
guaranteed with current C++ Compilers?
Thanks for any reply,
Falk Sticken
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net