From: Elad Lahav <e2lahav@gmail.com>
To: perfbook@vger.kernel.org
Subject: Ordering and conditionals
Date: Wed, 11 Jan 2023 11:09:14 -0500 [thread overview]
Message-ID: <CAJbg=FX8rBFRqO-3bhE863OepcdShoyGg0tVeedVR2=tfjwcDQ@mail.gmail.com> (raw)
Hello all,
Here's an interesting (hopefully!) question I came across. Consider
the following code:
int a = 0;
int b = 0;
void
writer()
{
a = 1;
write_barrier();
b = 2;
}
int
reader1()
{
for (;;) {
if (b == 2) {
return a;
}
yield();
}
}
int
reader2()
{
while (b == 2) {
yield();
}
return a;
}
The barrier issued by the writer ensures that if any reader observes b
== 2 then it must also observe a == 1. However, that is only true if
both the compiler and the processor agree that a is loaded after b.
Consider the two reader functions. These are pretty much the same from
C's point of view, but while the dependency between b and a is clear
in the first case it is less so in the second. I can see a compiler
loading a before the loop in reader2(), but less so in the case of
reader1(). Perhaps that's just the way I interpret the code and a
compiler would treat these as exactly the same.
Let's assume then that you change the code to do something like return
READ_ONCE(a) in both cases, as the book recommends. Does it change
anything for the compiler? Does it change anything for the processor,
which can reorder the reads? Anecdotally, it seems that a read barrier
helps with reader2(), but I would not expect it to be needed for
reader1().
Thoughts?
--Elad
next reply other threads:[~2023-01-11 16:09 UTC|newest]
Thread overview: 2+ messages / expand[flat|nested] mbox.gz Atom feed top
2023-01-11 16:09 Elad Lahav [this message]
2023-01-11 22:20 ` Ordering and conditionals Akira Yokosawa
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to='CAJbg=FX8rBFRqO-3bhE863OepcdShoyGg0tVeedVR2=tfjwcDQ@mail.gmail.com' \
--to=e2lahav@gmail.com \
--cc=perfbook@vger.kernel.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).