Re: A question about synchronized threads
On 4/29/2011 12:12 PM, byhesed wrote:
If too much spaces are marked as critical regions,
then the program will not be optimized.
It wastes too much time in waiting for obtaining a right to access
So, in my question, better means optimization when using threads.
A bit of advice I've found *very* useful over the years: Don't
think about protecting "critical regions of code," think instead
about protecting "access to shared data."
Stop. Go back and read the paragraph again. It's the crux.
Threads T1,T2,...,Tn do not interfere by executing the same
code simultaneously, but by trying to access the same data. (More
generally, by trying to access the same "state.") If the shared
state is S, then T1,T2,...,Tn must not try to alter it at the same
time, nor try to read it while another Tx is altering it. If, on
the other hand, S decomposes into disjoint sub-states S1,S2,...,Sm
that are *completely* independent, then it's all right for Ti to
alter Sa while Tj reads Sb; you must guard against simultaneous
alteration or alteration-and-read of each single sub-state Sx.
Think about the state; that's what you're trying to keep
coherent and consistent. Don't worry about the code; it's just
the tool that manipulates the state. You'll be astonished at how
much simpler things become with this view. Trust me.