Channels in Objective-C
In Objective-C, we can use Grand Central Dispatch (GCD) to achieve similar functionality to Go’s channels. GCD provides a way to manage concurrent operations and communicate between different parts of your code.
In this Objective-C example:
We create a concurrent dispatch queue using
dispatch_queue_create
. This is similar to creating a channel in Go.We use a dispatch semaphore (
dispatch_semaphore_t
) to synchronize operations between the sending and receiving of the message. This helps us achieve similar behavior to Go’s channel send and receive operations.We declare a
__block NSString *message
to hold our message. The__block
specifier allows the variable to be modified within the block.We dispatch an asynchronous task using
dispatch_async
. This is similar to launching a goroutine in Go. Inside this task, we set the message and signal the semaphore.We use
dispatch_semaphore_wait
to wait for the message to be sent. This is similar to receiving from a channel in Go.Finally, we print the received message using
NSLog
.
When we run the program, the “ping” message is successfully passed from one asynchronous task to the main thread via our dispatch queue and semaphore.
By default, the dispatch semaphore allows us to synchronize the sending and receiving of the message, similar to how channel sends and receives block in Go until both the sender and receiver are ready. This property allowed us to wait at the end of our program for the “ping” message without having to use any other synchronization mechanism.