🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: borland.public.cppbuilder.nativeapi
Article #795

Re: ensuring CriticalSections are release..

#795
From: Dennis Jones
Date: Mon, 14 Jan 2008 06:26
38 lines
2430 bytes
"Mike Collins" <its@TheBottomOfThePost> wrote in message 
news:478a96e3@newsgroups.borland.com...
> Hay all, just a quicky, just wondering if anyone had any thoughts on using 
> try... __finally to ensure that a critical section is always released?
>
> I have a thread with a getter and setter to provide access to a private 
> variable.  I use a CRITICAL_SECTION to ensure thead-safety but i wasn't 
> sure about whether or not to use a try.. __finally to ensure that the CS 
> always gets released...

Besides the fact that try/finally is non-standard, it has also had bugs in 
the past, so I would not trust it *at all*.  In the vein of using RAII as 
Bob and Alan have suggested, my personal preference is to use ScopeGuard. 
ScopeGuard lets you create unnamed, stack-based objects that will invoke any 
function or method upon exiting the current, local scope.  For example:

#include "ScopeGuard.h"

void DoSomethingWithCritSect( TCriticalSection *pCritSect )
{
    pCritSect->Acquire();
    ON_BLOCK_EXIT_OBJ( *pCritSect, &TCriticalSection::Release );

    // code relying on the critical section goes here

} // <== pCritSect->Release is invoked here, regardless of how scope was 
exited

An article discussing the implementation and use of ScopeGuard was written 
by Andrei Alexandrescu and Petru Marginean and was published in CUJ in 
December 2000.  You can read it here:  http://www.ddj.com/dept/cpp/184403758

and get the source here:

ftp://66.77.27.238/sourcecode/cuj/2000/cujdec2000.zip

- Dennis 
Technical Details
Message-ID: <478b0076$1@newsgroups.borland.com>
Path: arc1-ca.pugleaf.net!g2news1.google.com!news1.google.com!news2.google.com!news.glorb.com!newsfeeds.ihug.co.nz!ihug.co.nz!newsgroups.borland.com!not-for-mail
References: <478a96e3@newsgroups.borland.com>

Show Full Headers
Complete Article Headers
X-Google-Thread: 10cc67,266d339b0fd4ba38
X-Google-Attributes: gid10cc67,public,usenet
X-Google-Language: ENGLISH,ASCII-7-bit
From: "Dennis Jones" <nospam@nospam.com>
Newsgroups: borland.public.cppbuilder.nativeapi
References: <478a96e3@newsgroups.borland.com>
Subject: Re: ensuring CriticalSections are release..
Date: Sun, 13 Jan 2008 22:26:00 -0800
Lines: 40
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2900.3138
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3198
X-RFC2646: Format=Flowed; Response
NNTP-Posting-Host: 71.245.109.58
Message-ID: <478b0076$1@newsgroups.borland.com>
X-Trace: newsgroups.borland.com 1200291958 71.245.109.58 (13 Jan 2008 22:25:58 -0700)
Path: arc1-ca.pugleaf.net!g2news1.google.com!news1.google.com!news2.google.com!news.glorb.com!newsfeeds.ihug.co.nz!ihug.co.nz!newsgroups.borland.com!not-for-mail