DevOps SRE Coding Interview Question 77 Goroutines in Golang

Sdílet
Vložit
  • čas přidán 13. 09. 2024
  • Hey everyone, today's DevOps question is a simple coding task. We need to run three different goroutines in a Go program.
    What is a Goroutine?
    A goroutine is like a small task that can run independently but within the same Go program. You can start multiple tasks (goroutines) that run simultaneously and finish independently.
    Setting Up the Program
    Start with the Package Declaration:
    Begin by declaring the main package.
    Import Necessary Packages:
    Import the fmt package for printing output and the time package for managing wait times.
    Writing the Main Function
    Define the Main Function:
    In the main function, start three goroutines to print different messages concurrently. After starting the goroutines, use a sleep function to ensure the main program waits for the goroutines to complete before exiting.
    Creating the Print Function
    Define the Print Function:
    Create a function that takes a string as input and prints it.
    Running the Program
    When you run this program, it starts three goroutines that print messages concurrently. Using a sleep function ensures that the main program waits for all goroutines to complete before exiting.
    Explanation
    Package Declaration: Start by declaring the main package.
    Imports: Import fmt for printing and time to control the program’s execution time.
    Main Function:
    Start three goroutines with the print function, each printing a different message.
    Use a sleep function to wait for 2 seconds, allowing the goroutines to finish.
    Print Function: Create a function that prints the string passed to it.
    When you run the code, the messages may print in any order because goroutines run concurrently. This demonstrates how tasks can run simultaneously in Go.

Komentáře •