|
From: Leif W. <lei...@gm...> - 2012-12-05 21:52:09
|
Sent from my iPhone
On Dec 5, 2012, at 16:31, "Patrick J. LoPresti" <lop...@gm...> wrote:
> On Wed, Dec 5, 2012 at 10:29 AM, Leif Walsh <lei...@gm...> wrote:
>> Here are the threads I have:
>>
>> {
>> pthread_rwlock_rdlock();
>> x = 1;
>> pthread_rwlock_rdunlock();
>> }
>>
>> {
>> pthread_rwlock_wrlock();
>> if (x) {
>> x = 0;
>> } else {
>> foo();
>> }
>> pthread_rwlock_wrunlock();
>> }
>
> I am going to repeat myself a bit because this is an important point.
> Then I will give up.
>
> First, this code smells on its surface. If I were interviewing a
> candidate who submitted this as a code sample, it would be an easy
> "strong no hire" decision.
Ouch.
> Grabbing a reader lock to write a
> variable? What the heck is that?
It's an eviction heuristic. It doesn't even need to be perfectly accurate.
>
> No matter how smart you think you are, sooner or later, you will work
> with people who lack your genius. Truly smart programmers write code
> that any idiot can prove correct. This does not qualify, to put it
> mildly.
>
> Second, as we keep trying to explain, concurrent writes to the same
> location are *undefined behavior* under every common threading model
> (including, in particular, POSIX and C++11). That means a compiler
> looking at this code can PROVE that only one thread ever runs the
> first block concurrently. If that is not true, then you have
> introduced a contradiction into the compiler's reasoning. "From a
> contradiction, anything follows." How badly this code breaks depends
> only on how smart your compiler is, and they get smarter all the time.
Try to sell a compiler that generates a random executable just because it proves undefined behavior.
I'm not trying to be (that) snarky, just realistic. I understand the risk you're describing and I appreciate you taking the time to do so. But adding extra fences here just because some theoretical compiler might turn this code into a giraffe drawing program is not a useful way for me or the CPU running my program to spend our time.
>
>> Boehm's paper did not convince me of a bug.
>
> When dealing with multi-threading, the right question is not "Do I
> fail to see the problem?" The right question is "Can I create a
> simple proof that there is no problem?"
>
> In my experience, most programmers either get this right away, or they
> never will.
>
>> Since pthread locks will include proper mfences I believe this to be correct
>> even on non-x86 machines.
>
> (a) You believe incorrectly, because undefined behavior can result in
> anything whatsoever.
>
> (b) Even if you were correct, the chain of reasoning to prove it is
> too long for maintainable code.
>
> Anyway, Helgrind is perfectly correct to warn about this bug.
It is.
>
> - Pat
|