This is the mail archive of the libc-help@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: thread safety level of fwide


On Nov 19, 2014, MaShimiao <mashimiao.fnst@cn.fujitsu.com> wrote:

> If it hasn't be decided (when _mode is zero), and there are two threads.
> Thread A wants to set _mode as 1.
> Thread B wants to set _mode as -1.

In this case, the initial test will not succeed, so we will grab the
lock and call _IO_fwide, that will repeat the test with the lock held.
So whichever thread grabs the lock first will succeed in making the
change, and the other will either grab the lock and, in _IO_fwide,
notice the mode is already set and return it, or notice that even before
grabbing the lock, returning it right away.

> can that be regard as data race? Or is it possible?

Technically, the unguarded test is a data race, but it is benign.  Here
are the possibilities:

1. the test sees the stream mode is already set, so we return it right
away;

2. the test sees the stream mode is undecided, and the caller wants to
set it, so we take the lock and call _IO_fwide, ensuring that only the
first to take the lock will succeed in changing the mode;

3. the test sees the stream mode is undecided (zero), and the caller
does not want to set it, so we return the mode, but there are 3
situations to analyze here:

3.a. nobody else has tried to change the value concurrently, so the zero
we see in the stream's mode is definitely the right thing to return

3.b. another thread is concurrently setting the mode, but due to the
lack of synchronization, our view of the stream memory remains at the
zero, and we return that; absent synchronization, nothing guarantees the
mode setting happened-before our fwide call, so it can't be wrong to
behave as-if our fwide call happened-before the concurrent mode setting

3.c. another thread is concurrently setting the mode, and by chance we
reload the stream mode even after we observed it as zero, and the reload
observes the value modified by the other thread; absent synchronization,
nothing guarantees mode setting happened-after our fwide call, so it
can't be wrong to behave as-if our fwide call happened-after the
concurrent mode setting.

So you see in all cases we get a reasonable value, never being harmed by
the data race in the lock-avoidance test.

-- 
Alexandre Oliva, freedom fighter    http://FSFLA.org/~lxoliva/
You must be the change you wish to see in the world. -- Gandhi
Be Free! -- http://FSFLA.org/   FSF Latin America board member
Free Software Evangelist|Red Hat Brasil GNU Toolchain Engineer


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]