Skip to content

Commit 7dd6c03

Browse files
committed
you're doing great
1 parent e951067 commit 7dd6c03

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Concurrency & Race Conditions
2+
3+
## Could this code cause a race condition?
4+
5+
```
6+
go cleanSessions()
7+
```
8+
9+
```
10+
func cleanSessions() {
11+
for k, v := range dbSessions {
12+
if time.Now().Sub(v.lastActivity) > (time.Second * 30) {
13+
delete(dbSessions, k)
14+
}
15+
}
16+
dbSessionsCleaned = time.Now()
17+
}
18+
19+
```
20+
21+
https://golang.org/doc/go1.6 says:
22+
23+
"The runtime has added lightweight, best-effort detection of concurrent misuse of maps. As always, if one goroutine is writing to a map, no other goroutine should be reading or writing the map concurrently. If the runtime detects this condition, it prints a diagnosis and crashes the program. The best way to find out more about the problem is to run the program under the race detector, which will more reliably identify the race and give more detail."
24+
25+
When you
26+
27+
```
28+
go build -race
29+
```
30+
31+
you do not get a race condition reported.
32+
33+
34+
![no race condition](norace.png)
35+
36+
So if you're not writing to a map, you can use the map concurrently without a problem.
37+
38+
RE: time.Time
39+
40+
"A Time value can be used by multiple goroutines simultaneously."
41+
42+
https://godoc.org/time#Time
43+
44+
## Expanding on maps & goroutines
45+
46+
Maps are funky.
47+
48+
Check this out:
49+
50+
![maps are funky](maps.png)
51+
52+
53+
https://play.golang.org/p/62DF4xvPeQ
54+
55+
**So you can delete something that doesn't exist, and that is not a problem.**
56+
57+
**And you can ask for something that isn't there, and that is not a problem (gives you the zero value for the map's value).**
58+
59+
Deleting IS DIFFERENT from writing.
60+
61+
**If more than 1 goroutine tried to delete that same entry in the map: no problem.**
62+
63+
**And if you're reading from the map and a value isn't there: no problem.**
64+
65+
So why is WRITING a problem with concurrency?
66+
67+
The classic race condition example is two routines READING, pulling the same value, each incrementing the value, and then each WRITING the incremented value back, and the value is incremented only 1, instead of 2.
68+
69+
Just remember: WRITE TO MAP = concurrency considerations.
65.1 KB
Loading
369 KB
Loading

0 commit comments

Comments
 (0)