> Actually, your other posts just say wrong, wrong, wrong. None of them
> explain how a critical section works (or should), other than that they
> are used to safely access something from more than one thread... which
> we already knew, since that's why I'm trying to use one in the first
> place.

OK, sorry for being such a wrong-wronger!  :-)

Here's how a critical section (CS) works.  You have resources which must
only be accessed by one thread at a time, and all of those resources run
inside the same process.  You define a CS to protect that resource.  When
thread1 calls the Lock( ) method, a special x86 instrcution is executed
which simlates the 'lock' being on.  Now, thread1 is said to have "entered
the CS."  Now, thread2 gets to the point where it needs access to that
resource, so it calls Lock( ) on the same CS object again.  Now, the x86
instrcution locks this thread, because it detects that the CS is already
being in 'lock' mode.  From this point on, thread2 is put to sleep.  Now,
thread1 finishes its job with the resource, and calls Unlock( ), which
resets the 'lock' flag.  When thread2 gets its next time slice, it's woken
up, and again the 'lock' flag is set, and Lock( ) returns.  Now, thread2
goes on accessing the resource.  If now, thread1 (or a thread3) attempts to
Lock( ) the CS again, it's put to sleep like thread2 was.  After thread2
finishes up and calls Unlock( ) again, the 'lock' flag is cleared and the
resource is free to be accessed from the same (or other) thread(s).

Now, it's clear why you should use prosen's suggestion, because it ensures
that the Unlock( ) is called no matter what happens (e.g an exception is
thrown.)  Just imagine that a thread holding a lock faces an exception, and
execution gets resumed from some point upper in the call stack.  Now, no
other threads can access the resource until the app is terminated.  That's
not what is desirable to you, of course.

-------------
Ehsan Akhgari

Farda Technology (http://www.farda-tech.com/)

List Owner: [EMAIL PROTECTED]

[ Email: [EMAIL PROTECTED] ]
[ WWW: http://www.beginthread.com/Ehsan ]

"In Heaven an angel is nobody in particular."
 George Bernard Shaw





Reply via email to