0
0
Goprogramming~30 mins

Why concurrency is needed in Go - See It in Action

Choose your learning style9 modes available
Why concurrency is needed
📖 Scenario: Imagine you run a small bakery. You have to bake bread, prepare cakes, and serve customers. Doing one task at a time makes customers wait longer. If you could do tasks at the same time, you would serve customers faster and keep them happy.
🎯 Goal: Build a simple Go program that shows how doing tasks one by one is slower than doing them concurrently. You will create tasks as functions, run them sequentially first, then run them concurrently using goroutines.
📋 What You'll Learn
Create three functions: bakeBread(), prepareCake(), and serveCustomer() that each print a message and wait 2 seconds.
Create a main function that calls these three functions one after another (sequentially).
Add a configuration variable useConcurrency to switch between sequential and concurrent execution.
Modify the main function to run the three tasks concurrently using goroutines if useConcurrency is true.
Print messages to show when each task starts and ends.
💡 Why This Matters
🌍 Real World
Concurrency is used in real life when you want to do many things at once, like cooking multiple dishes or serving many customers quickly.
💼 Career
Understanding concurrency is important for software developers to build fast and responsive programs, especially for web servers, games, and apps that handle many users.
Progress0 / 4 steps
1
Create task functions
Create three functions called bakeBread(), prepareCake(), and serveCustomer(). Each function should print a start message, wait for 2 seconds using time.Sleep(2 * time.Second), then print a done message.
Go
Hint

Use fmt.Println to print messages and time.Sleep to wait.

2
Add concurrency switch variable
Create a boolean variable called useConcurrency and set it to false. This will control if tasks run one by one or at the same time.
Go
Hint

Write useConcurrency := false inside main().

3
Run tasks sequentially or concurrently
In the main() function, write an if statement that checks if useConcurrency is false. If so, call bakeBread(), prepareCake(), and serveCustomer() one after another. Otherwise, run these three functions concurrently using goroutines and wait for all to finish using a sync.WaitGroup.
Go
Hint

Use sync.WaitGroup to wait for goroutines to finish when useConcurrency is true.

4
Print results and test concurrency
Add fmt.Println("Running tasks sequentially") before the sequential calls and fmt.Println("Running tasks concurrently") before the concurrent goroutines. Run the program twice: once with useConcurrency set to false and once with it set to true. Observe the difference in output timing.
Go
Hint

Print messages before running tasks to show if they run sequentially or concurrently.