Goroutines and concurrency in Go

 Goroutines and concurrency in Go


One of the most powerful features of Go is its built-in support for concurrency. Goroutines are lightweight threads that can be created and managed easily in Go.


To create a goroutine, you can simply prefix a function call with the go keyword:



func foo() {

    for i := 0; i < 10; i++ {

        fmt.Println(i)

    }

}


func main() {

    go foo()

    fmt.Println("main")

}

In this example, we create a new goroutine by using the go keyword to call the foo() function. The main function continues executing without waiting for the foo() function to complete.


Concurrency in Go is further supported by channels, which are used to communicate and synchronize between goroutines. Channels are typed and can be used to send and receive values between goroutines.



func producer(ch chan<- int) {

    for i := 0; i < 10; i++ {

        ch <- i

    }

    close(ch)

}


func consumer(ch <-chan int) {

    for val := range ch {

        fmt.Println(val)

    }

}


func main() {

    ch := make(chan int)

    go producer(ch)

    consumer(ch)

}

In this example, we define two functions: producer and consumer. The producer function sends values to a channel, and the consumer function receives values from the channel.


We create a new channel by using the make() function, and we pass the channel to the producer and consumer functions by using the <- operator.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...