Re: malloc/free problems within a thread
Re: malloc/free problems within a thread
- Subject: Re: malloc/free problems within a thread
- From: "stephen joseph butler" <email@hidden>
- Date: Sat, 29 Jul 2006 17:43:40 -0500
2006/7/29, Ken Tozier <email@hidden>:
Perhaps a code snippet would clear up the sequence of events
// in the init method for a long lived class, I initialize a mutable
array
NSMutableArray *holdingBin = [[NSMutableArray alloc] init];
First, realize that NSMutableArray is not thread safe. That is, you
need to guarantee that no two threads are trying to access the array
at any given time (using NSLock, for example).
// Then I create a repeating timer
[NSTimer scheduledTimerWithTimeInterval: 5
target: self
selector: @selector(performDirectoryTasksWithTimer:)
userInfo: nil
repeats: YES];
return self
// When the timer fires, it calls performDirectoryTasksWithTimer
which is defined like so:
- (void) performDirectoryTasksWithTimer:(NSTimer *) inTimer
{
[NSThread detachNewThreadSelector: @selector(scanDirectoriesInThread:)
toTarget: self
}
// I create the thread because the scanning is pretty time consuming
(12 minutes on average) and I want the machine to be usable during
this time
// Here's the scanDirectoriesInThread definition (where I allocate an
autorelease pool)
Every 5 seconds you're creating a helper thread that will perform a 12
minute directory scan. See where I'm going with this?
- (void) scanDirectoriesInThread:(NSString *) inString
{
// allocate a new autorelease pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// map the directories
[self initDirectories];
// release the pool
[pool release];
}
// Which in turn calls the method that actually performs the scan
- (void) initDirectories
{
// The malloc/free happens in here and the data in the malloc'd
pointer is packed into an NSData and put in "holdingBin" allocated in
the init routine
[ holdingBin addObject: [NSData dataWithBytes: ptr length: len]];
// When I try to free pointers in here, I get those errors
}
See any obvious allocation related gotchas here?
Yes. You're spawning multiple threads, all of which are trying to
access the same mutable array without any sort of locking. This is
will most certainly cause random memory corruption.
You have a couple options:
1) allocate an NSLock along with the NSMutableArray and synchronize
access to your collection.
2) allocate a temporary NSMutableArray inside scanDirectoriesInThread:
and only after you're done assign it to holdingBin. However, you'll
want to release whatever's there, so you need a lock for holdingBin to
make sure you have exclusive access. That is...
[holdingBin lock];
[holdingBin release]; holdingBin = nil;
holdingBin = tempArray;
[holdingBin unlock];
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden