Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

2 snippets
  • Goroutines in Go

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    func print(from string) {
    	for i := 0; i < 3; i++ {
    		fmt.Println(from, ":", i)
    	}
    }
    
    func main() {
    	// Synchronous function call
    	print("synchronous call")
    
    	// Asynchronous function call
    	// To run this function in a goroutine, use go f(s)
    	// This new goroutine will execute concurrently with the calling main goroutine
    	go print("asynchronous call")
    
    	// Goroutine can also be execute as an anonymous function
    	go func(msg string) {
    		fmt.Println(msg)
    	}("asynchronous anonymous call")
    
    	// Two previous function calls are now running asynchronously in separate goroutines
    	// Wait for them to finish
    	time.Sleep(time.Second)
    	fmt.Println("done")
    }
    
    // $ go run main.go
    // synchronous call : 0
    // synchronous call : 1
    // synchronous call : 2
    // asynchronous anonymous call
    // asynchronous call : 0
    // asynchronous call : 1
    // asynchronous call : 2
    // done

    Here is an example of goroutines in Golang.

  • Buffered and unbuffered channels in Go

    package main
    
    import "fmt"
    
    func main() {
        // Create unbuffered channel
    	unbufferedChannel := make(chan string)
    
    	go func() {
            // Send a value into a channel using the channel<- syntax
    		unbufferedChannel <- "unbuffered channel"
    	}()
    
        // The <-channel syntax receives a value from the channel
    	fmt.Println(<-unbufferedChannel)
    
        // Create buffered channel with size 2
    	bufferedChannel := make(chan string, 2)
    
        // Send a value to a buffered channel. The operation in non blocking
    	bufferedChannel <- "buffered"
    	bufferedChannel <- "channel"
    
    	fmt.Println(<-bufferedChannel)
    	fmt.Println(<-bufferedChannel)
    }
    
    // go run main.go 
    // unbuffered channel
    // buffered
    // channel

    Channels serve as pipes for communication between concurrent goroutines. They allow one goroutine to send values and another goroutine to receive those values. By default, sending and receiving operations block until both the sender and receiver are ready. This feature enabled us to wait for the "unbuffered channel" message at the end of our program without needing any additional synchronization mechanisms. Buffered channels can hold a limited number of values without requiring an immediate receiver.