Re: WaitForSingleObject() will not deadlock
On Thu, 05 Jul 2007 23:24:32 -0400, Joseph M. Newcomer
<newcomer@flounder.com> wrote:
Yes, but you also said that there was an issue if the line was uncommented.
Because there *is* an issue.
Since with
the line commented out, and assuming there is no other gratuitous assignment to x, then it
is completely deterministic
Then why did you say the code is "erroneous" and has a "race condition"?
Neither is true, as is clear when you read the explanation that came with
the example. Let me try once again:
********************
It makes sense. Here's an illustration of what it's saying:
int x = 0; // global
***** Thread 1:
x = 2;
CreateThread;
// x = 3;
***** Thread 2:
if (x == 2)
puts("x == 2");
A. Rule (1) guarantees that when started, thread 2 observes x == 2, since
thread 1 set it to 2 before creating the second thread.
B. However, if you were to uncomment the line that sets x to 3, thread 2
might not see that value, even if it were executed before thread 2 got
around to testing it. That is, thread 2 might still observe the value 2,
even though from thread 1's perspective, x contains 3, at the moment thread
2 tested it.
********************
I've now split the discussion into parts (A) and (B). Part (A) is talking
about the example *as given*, with the line commented *out*. Part (B) is
talking about the example after *uncommenting* the line. Part (A) discusses
what Rule (1) guarantees. Part (B) discusses what it does not guarantee. I
don't see how I could more directly illustrate Rule (1), which is:
1. Whatever memory values a thread can see when it creates a new thread can
also be seen by the new thread once it starts. Any data written to memory
after the new thread is created may not necessarily be seen by the new
thread, even if the write occurs before the thread starts.
Make sense?
Lacking the ability to see the pages, it was not obvious what was on them.
The point is, understanding what those pages discuss is not necessary to
understand the 4 rules which were phrased in terms of mutexes and condition
variables. Put another way, as long as you follow the 4 rules, you can get
by in pthreads having never heard of a memory barrier or cache consistency.
I posted the rules after you asked how to define "memory visibility". They
constitute one such definition, and if you limit yourself to thread
creation/join and mutexes, they apply equally well to Windows as they do to
POSIX. I also posted a link to an MSDN page that talked about the
lower-level concepts.
--
Doug Harrison
Visual C++ MVP