Goroutines
Creating Goroutines: - Use the "go" keyword in front of function call - When using anonymous functions, pass data as local variables Synchronization: - Use sync.WaitGroup to wait for groups of goroutines to complete - Use sync.Mutex and sync.RWMutex to protect data access Parallelism: - By default, Go will use CPU threads equal to available cores - Change with runtime.GOMAXPROCS - More threads can increase performance, but too many can slow it down Best Practices: - Don't create goroutines in libraries - Let consumer control concurrency - When creating a goroutine, know how it will end - Avoids subtle memory leaks - Check for race conditions at compile time
Channels
Channel Basics: - Create a channel with the make command - make(chan int) - Send message into channel - ch <= val - Receive message from channel - val := <-ch - Can have multiple senders and receivers Restricting Data Flow: - Channels can be case into send-only or receive-only versions - Send-only: chan <- int - Receive-only: <-chan int Buffered Channels: - Channels block sender side until receiver is available - Block receiver side until message is available - Can decouple sender and receiver with buffered channels - make(chan int, 50) - Use buffered channels when send and receiver have assymmetric loading Select Statements: - Allows goroutine to monitor several channels at once - Blocks if all channels block - If multiple channels receive value simultaneously, behavior is undefined
