Re: [NSLock dealloc] Exception
Re: [NSLock dealloc] Exception
- Subject: Re: [NSLock dealloc] Exception
- From: Bing Li <email@hidden>
- Date: Sat, 21 May 2011 00:15:34 +0800
Dear Nick and all,
Thanks so much for your replies!
I have got the reason of the exception. When sending a message successfully,
SendMessage is returned without unlocking. The structure, try/catch/finally,
is a good solution to the potential problem.
Best regards,
Bing
On Fri, May 20, 2011 at 11:26 PM, Nick Zitzmann <email@hidden> wrote:
>
> On May 20, 2011, at 9:11 AM, Bing Li wrote:
>
> > Dear all,
> >
> > I am implementing a TCP client to send messages with BSD sockets. A BOOL
> > variable, isConnected, is used to detect if the TCP connection is built.
> > Since the client must be accessed by multiple threads, a NSLock,
> > isConnectedLock is used.
> >
> > When testing, after invoking the methods, Connect and SendMessage, I
> release
> > the client. However, I got an exception as follows.
> >
> > **** -[NSLock dealloc]: lock (<NSLock: 0x100614cc0> '(null)') deallocated
> > while still in use*
> >
> > **** Break on _NSLockError() to debug.*
> >
> > What is the potential problem?
> >
> > Thanks so much!
> > Bing
> >
> > - (BOOL) Connect
> > {
> > [isConnectedLock lock];
> > if (!isConnected)
> > {
> > destinationSocket = socket(AF_INET, SOCK_STREAM,
> > IPPROTO_TCP);
> > if (destinationSocket < 0)
> > {
> > return NO;
> > }
> >
> > memset(&destinationAddress, 0,
> sizeof(destinationAddress));
> > destinationAddress.sin_family = AF_INET;
> > const char *ip = [DestinationIP UTF8String];
> > int isAddressValidate = inet_pton(AF_INET, ip,
> > &destinationAddress.sin_addr.s_addr);
> > if (isAddressValidate == 0)
> > {
> > return NO;
>
> Here, and at several other places, you are returning without unlocking
> first.
>
> This is why I recommend wrapping locks in an exception handler, with the
> lock being unlocked in the "finally" part of the handler, so that the lock
> will always be unlocked, even if you return inside the function/method or an
> exception gets thrown. Like this:
>
> [theLock lock];
> @try
> {
> // do stuff here
> }
> @catch (NSException *e)
> {
> // maybe do something here, or re-throw the exception
> }
> @finally
> {
> [theLock unlock];
> }
>
> Nick Zitzmann
> <http://www.chronosnet.com/>
>
>
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden