Goroutines in Go

Go: Goroutines

Goroutines are a feature of Go that allow for concurrent execution of functions. They are lightweight threads that are managed by the Go runtime, and they enable programmers to write concurrent and parallel code in a simple and efficient way.

How to create a goroutine in Go

To create a goroutine in Go, we simply needs to add the keyword go in front of a function call, like this:

    func hello() {
        fmt.Println("Hello, world!")
    }

    func main() {
        go hello()
        fmt.Println("main function")
        time.Sleep(time.Second)
    }

How Goroutines communicates with each other

Goroutines can communicate with each other using channels, which are a built-in type in Go.

Channels allow goroutines to send and receive values between each other in a safe and synchronized way.

Below is an example of how to use channels:

    func worker(id int, jobs <-chan int, results chan<- int) {
        for j := range jobs {
            fmt.Println("worker", id, "processing job", j)
            time.Sleep(time.Second)
            results <- j * 2
        }
    }

    func main() {
        jobs := make(chan int, 100)
        results := make(chan int, 100)

        for w := 1; w <= 3; w++ {
            go worker(w, jobs, results)
        }

        for j := 1; j <= 9; j++ {
            jobs <- j
        }
        close(jobs)

        for a := 1; a <= 9; a++ {
            <-results
        }
    }

In this example, we define a worker function that takes an ID, a channel of jobs to process, and a channel to send the results back on. The worker function processes each job by sleeping for one second and then sending back the result of doubling the job value.

In the main function, we create two channels: one for jobs and one for results. We then create three worker goroutines and pass them the channels to use. We send nine jobs on the jobs channel, close the channel to indicate that we're done sending jobs, and then receive the nine results from the results channel. The output of this program will show the worker goroutines processing the jobs in parallel and sending the results back through the channel.

goroutines and channels are powerful features of Go that enable programmers to write concurrent and parallel code in a safe and efficient way.

Previous Article

Next Article