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.go206 chars10 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.go311 chars15 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