Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: A question about synchronized threads Date: Fri, 29 Apr 2011 21:01:07 -0400 Organization: A noiseless patient Spider Lines: 33 Message-ID: References: <3f249d87-aaf8-4732-9ee8-fd112cf82553@f31g2000pri.googlegroups.com> <8b7289b0-2b52-44f9-96a9-fe1d2661de11@k3g2000prl.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Sat, 30 Apr 2011 01:01:42 +0000 (UTC) Injection-Info: mx03.eternal-september.org; posting-host="KiwfXDyOjqGhZBXcfNnZBg"; logging-data="17389"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/sIPgvLI2osanAYWCgmxek" User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.15) Gecko/20110303 Thunderbird/3.1.9 In-Reply-To: <8b7289b0-2b52-44f9-96a9-fe1d2661de11@k3g2000prl.googlegroups.com> Cancel-Lock: sha1:pTDVWSnweY8y94dTYpjfUomb6gE= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:3369 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 > critical regions. > > 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. -- Eric Sosman esosman@ieee-dot-org.invalid