Content
- Goroutine
- sync.WaitGroup
- sync.Mutex => to fix
+ Race Condition (using: mu.Lock(), mu.Unlock())
+ Deadlock (using: mu.Lock(), mu.Unlock())
A goroutine is a lightweight thread managed by the Go runtime. It allows you to run functions concurrently—at the same time—as other code.
What is a goroutine?
In Go, when you use the keyword go before a function call, it runs that function in a new goroutine.
Think of it as telling Go:
“Hey, start this function in the background. I’ll keep doing other stuff while it runs.”
Keyword
-
go— this is the keyword to create a goroutine.
Basic Syntax
Or with an anonymous function:
Simple Example
What Happens Here:
-
main()starts. -
go sayHello()starts thesayHello()function concurrently. -
main()keeps running and prints its own message. -
time.Sleep()keeps the program running long enough to see the output from the goroutine.
sync.WaitGroup?
Think of sync.WaitGroup like a counter that helps your program wait until all background tasks (goroutines) are done.
Output
Summary
| Keyword | Meaning |
|---|---|
sync.WaitGroup | Tool to wait for goroutines |
wg.Add(n) | Say “I’m waiting for n tasks” |
wg.Done() | Say “I’m finished with my task” |
wg.Wait() | Pause until all tasks are done |
Race Condition
Simple Definition:
A race condition happens when two or more goroutines access the same variable at the same time, and at least one of them writes to it.
Think of:
Two kids writing on the same whiteboard at the same time — the result is a mess.
Simple Example (with Race Condition):
Problem:
You expect count = 2000, but it might be 1792, 1900, 2000, etc.
Because:
-
Both goroutines read and write at the same time.
-
They "race" to access
count.
Fix with sync.Mutex (Mutual Exclusion Lock)
2. Deadlock
Simple Definition:
A deadlock happens when two or more goroutines are waiting for each other, and none can move forward.
Think of:
Two people trying to pass each other in a narrow hallway but both freeze, waiting forever.
Simple Deadlock Example:
Problem:
-
mu.Lock()is called twice withoutmu.Unlock(). -
The second
.Lock()waits forever → program hangs.
Deadlock with Channels
❗ Why?
-
You’re sending a value to the channel.
-
But no goroutine is receiving from it → it waits forever.
No comments:
Post a Comment