Go Routines and Channels

Go Routines and Channels

Go routines and channels are fundamental concepts in Go programming language for handling concurrency.

Go Routines

A Go routine is a lightweight thread of execution. The go keyword is used to create a Go routine.

go funcName()        

This will start a new Go routine that executes funcName() concurrently.

Channels

Channels are the pipes that connect concurrent goroutines. You can send values into channels from one goroutine and receive those values into another goroutine.

Creating a Channel

You can create a channel using the make command.

ch := make(chan int)        

This creates a channel that can transport integers.

Sending and Receiving from a Channel

The <- operator is used to send and receive data in channels.

ch <- v    // Send v to channel ch.
v := <-ch  // Receive from ch, and assign value to v.        

Example

Here is an example of using Go routines and channels.

package main

import (
    "fmt"
    "time"
)

func worker(done chan bool) {
    fmt.Print("working...")
    time.Sleep(time.Second)
    fmt.Println("done")

    // Send a value to notify that we're done.
    done <- true
}

func main() {
    // Start a worker goroutine, giving it the channel to notify on.
    done := make(chan bool, 1)
    go worker(done)

    // Block until we receive a notification from the worker on the channel.
    <-done
}        

In this example, worker is a Go routine that takes a channel as a parameter. It does some work, then sends a value on the channel to signal that it's done. The main function waits for the worker to finish before exiting.

Remember, by default sends and receives block until both the sender and receiver are ready. This property allowed us to wait at the end of our program for the "done" message without having to use other synchronization mechanisms like WaitGroups or Mutexes.


要查看或添加评论,请登录

Sreenivasulu Bodanapati的更多文章

社区洞察

其他会员也浏览了