This is correct code, after Martins instructions.
AppDelegate.h:
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
{
volatile int32_t sharedIndex; // Shared between threads, current index in array
NSOperationQueue* operationQueue;
}
@property (assign) IBOutlet NSWindow *window;
// Shared between threads, list of words
@property (atomic, retain) NSArray* sharedListWords;
- (void)worker;
@end
AppDelegate.m:
#import "AppDelegate.h"
@implementation AppDelegate
- (IBAction)btnRun:(id)sender
{
// Read txt file dictionary of words, where is each words in new line.
NSString* dictionaryFilePath = [NSString stringWithFormat:@"/Users/admin/dictionary.txt"];
NSString* fileContents = [NSString stringWithContentsOfFile:dictionaryFilePath
encoding:NSUTF8StringEncoding error:nil];
// Get array of string separated by new line
self.sharedListWords = [fileContents componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
//self.sharedListWords = @[@"one",@"two",@"three",@"four",@"five",@"six",@"seven",@"eight",@"nine",@"ten"];
self->sharedIndex = -1;
int numberOfThreads = 2;
NSOperation* jobFinishedOper = [[NSInvocationOperation alloc]
initWithTarget:self selector:@selector(jobFinished) object:nil];
// Run method working() in separate threads
for(int i=0; i<numberOfThreads; ++i)
{
//////////////////////////////////////////
// Create a thread
// Create new NSOperatin object with function puting in @selector() for run in other thread.
NSOperation* startBruteOper = [[NSInvocationOperation alloc]
initWithTarget:self selector:@selector(worker) object:nil];
// Add the operation to the queue and let it to be executed.
[operationQueue addOperation:startBruteOper];
[jobFinishedOper addDependency:startBruteOper]; // 'jobFinishedOper' run only when 'startBruteOper' finished!
[startBruteOper release];
/////////////////////////////////////////
}
// 'jobFinishedOper' run only when all prevous operation is finished!
[operationQueue addOperation:jobFinishedOper];
[jobFinishedOper release];
}
- (void)worker
{
unsigned long countWords = [self.sharedListWords count];
int32_t index = 0;
// Use atomic operation for thread safe
while( (index = OSAtomicIncrement32( &(self->sharedIndex) ) ) < countWords )
{
NSLog(@"[%@] working on \"%@\"",
[NSThread currentThread],
[self.sharedListWords objectAtIndex:index]);
}
NSLog(@"[%@] work is finish.", [NSThread currentThread]);
}
- (void)jobFinished
{
self.sharedListWords = nil;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Multithreading queue list
operationQueue = [[NSOperationQueue alloc] init];
}
@end