create multiple goroutines in go

To create multiple goroutines in Go, we can use the go keyword followed by a function call or a function literal.

Here's an example of how to create two goroutines that print a message and a number concurrently:

main.go
func printMessage(message string, number int) {
    fmt.Printf("%s %d\n", message, number)
}

func main() {
    go printMessage("Hello", 1)
    go printMessage("World", 2)
    time.Sleep(1 * time.Second)
}
206 chars
10 lines

In the code snippet above, we define a function printMessage that takes a message and a number as arguments and prints them using fmt.Printf. In the main function, we create two goroutines using the go keyword and call printMessage with different arguments.

Finally, we add time.Sleep(1 * time.Second) to allow the goroutines to finish execution before the main function exits.

We can also use channels to synchronize the execution of multiple goroutines. Here's an example:

main.go
func printMessage(message string, number int, c chan string) {
    c <- fmt.Sprintf("%s %d", message, number)
}

func main() {
    c1 := make(chan string)
    c2 := make(chan string)
    
    go printMessage("Hello", 1, c1)
    go printMessage("World", 2, c2)
    
    fmt.Println(<-c1)
    fmt.Println(<-c2)
}
311 chars
15 lines

In this example, we define a function printMessage that takes a message, a number, and a channel as arguments. The function sends a formatted string to the channel.

In the main function, we create two channels c1 and c2. We then create two goroutines using the go keyword and call the printMessage function with different arguments and channels.

Finally, we read from the channels using the <- operator, which blocks until the message is available. This way, we ensure that the goroutines finish execution before the main function exits.

gistlibby LogSnag