Goroutines in Objective-C

A goroutine is a lightweight thread of execution. In Objective-C, we can use NSThread to achieve similar functionality. Here’s the translated code example:

#import <Foundation/Foundation.h>

void f(NSString *from) {
    for (int i = 0; i < 3; i++) {
        NSLog(@"%@: %d", from, i);
    }
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Call the function synchronously
        f(@"direct");
        
        // Call the function in a new thread
        [NSThread detachNewThreadSelector:@selector(performSelectorOnMainThread:withObject:waitUntilDone:) toTarget:[NSBlockOperation blockOperationWithBlock:^{
            f(@"NSThread");
        }] withObject:nil];
        
        // Call an anonymous function in a new thread
        [NSThread detachNewThreadWithBlock:^{
            NSLog(@"Anonymous function: going");
        }];
        
        // Allow time for the threads to finish
        [NSThread sleepForTimeInterval:1.0];
        
        NSLog(@"done");
    }
    return 0;
}

Suppose we have a function call f(NSString *from). Here’s how we’d call that in the usual way, running it synchronously.

f(@"direct");

To invoke this function in a new thread, we use NSThread. This new thread will execute concurrently with the calling one.

[NSThread detachNewThreadWithBlock:^{
    f(@"NSThread");
}];

You can also start a new thread for an anonymous function call.

[NSThread detachNewThreadWithBlock:^{
    NSLog(@"Anonymous function: going");
}];

Our two function calls are running asynchronously in separate threads now. Wait for them to finish.

[NSThread sleepForTimeInterval:1.0];
NSLog(@"done");

When we run this program, we see the output of the blocking call first, then the output of the two threads. The threads’ output may be interleaved, because threads are being run concurrently by the Objective-C runtime.

$ ./myprogram
direct: 0
direct: 1
direct: 2
NSThread: 0
Anonymous function: going
NSThread: 1
NSThread: 2
done

Next we’ll look at other concurrency patterns in Objective-C programs.