Skip to content

Commit

Permalink
Fix race condition allowing operation to be added for a thread at the…
Browse files Browse the repository at this point in the history
… same time that the thread is exiting.
  • Loading branch information
rfm committed Jan 6, 2025
1 parent ccab2cd commit 1cdc60d
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions Source/NSOperation.m
Original file line number Diff line number Diff line change
Expand Up @@ -1039,7 +1039,22 @@ - (void) _thread: (NSNumber *) threadNumber
RELEASE(when);
if (NO == found)
{
break; // Idle for 5 seconds ... exit thread.
[internal->cond lock];
if ([internal->starting count] == 0)
{
// Idle for 5 seconds ... exit thread.
[[[NSThread currentThread] threadDictionary]
removeObjectForKey: threadKey];
[internal->lock lock];
internal->threadCount--;
[internal->lock unlock];
[internal->cond unlock];
break;
}
/* An operation was added in the gap between the failed wait for
* the condition and us unconditionally locking the condition, so
* we fall through to execute that operation.
*/
}

if ([internal->starting count] > 0)
Expand Down Expand Up @@ -1083,10 +1098,6 @@ - (void) _thread: (NSNumber *) threadNumber
}
}

[[[NSThread currentThread] threadDictionary] removeObjectForKey: threadKey];
[internal->lock lock];
internal->threadCount--;
[internal->lock unlock];
DESTROY(arp);
[NSThread exit];
}
Expand Down Expand Up @@ -1139,18 +1150,19 @@ - (void) _execute
*/
if (internal->threadCount < max)
{
internal->threadCount++;
NSInteger count = internal->threadCount++;
NSNumber *threadNumber = [NSNumber numberWithInteger: count];

NS_DURING
{
NSNumber *threadNumber = [NSNumber numberWithInteger: internal->threadCount - 1];
[NSThread detachNewThreadSelector: @selector(_thread:)
toTarget: self
withObject: threadNumber];
}
NS_HANDLER
{
NSLog(@"Failed to create thread for %@: %@",
self, localException);
NSLog(@"Failed to create thread %@ for %@: %@",
threadNumber, self, localException);
}
NS_ENDHANDLER
}
Expand Down

0 comments on commit 1cdc60d

Please sign in to comment.