You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Concurrency is the execution of multiple instruction sequences at the same time. In Go, concurrency is achieved using goroutines. A goroutine is a lightweight thread of execution managed by the Go runtime. You can launch a function as a goroutine by prefixing the function call with the `go` keyword.
4
+
5
+
```go
6
+
godbCall(i)
7
+
```
8
+
9
+
However, if we run the code like this, it will feel like nothing happened. Our program spawns these tasks in the background, doesn't wait for them to finish, and then exits the program before they are complete. This is where wait groups come in.
10
+
11
+
## WaitGroup
12
+
13
+
A WaitGroup is used to wait for a collection of goroutines to finish executing. The main goroutine calls `Add` to set the number of goroutines to wait for. Then each of the goroutines runs and calls `Done` when finished. At the same time, `Wait` can be used to block until all goroutines have finished.
14
+
15
+
```go
16
+
varwg = sync.WaitGroup{}
17
+
18
+
funcmain(){
19
+
fori:=0; i<len(dbData); i++{
20
+
wg.Add(1)
21
+
godbCall(i)
22
+
}
23
+
wg.Wait()
24
+
}
25
+
```
26
+
27
+
## Mutex
28
+
29
+
A Mutex, or a mutual exclusion lock, is a synchronization primitive that can be used to protect shared data from being concurrently accessed by multiple goroutines. In Go, `sync.Mutex` is used for this purpose.
30
+
31
+
```go
32
+
varm = sync.Mutex{}
33
+
34
+
funcsave(resultstring){
35
+
m.Lock()
36
+
results = append(results, result)
37
+
m.Unlock()
38
+
}
39
+
```
40
+
41
+
However, one drawback of a mutex is that it completely locks out other goroutines from accessing a result slice. This is where `sync.RWMutex` comes in.
42
+
43
+
## RWMutex
44
+
45
+
`sync.RWMutex` is a reader/writer mutual exclusion lock. The lock can be held by an arbitrary number of readers or a single writer. It has `RLock` and `RUnlock` methods for reading, and `Lock` and `Unlock` methods for writing.
46
+
47
+
```go
48
+
varm = sync.RWMutex{}
49
+
50
+
funcsave(resultstring){
51
+
m.Lock()
52
+
results = append(results, result)
53
+
m.Unlock()
54
+
}
55
+
56
+
funclog(){
57
+
m.RLock()
58
+
fmt.Printf("\nThe current results are: %v", results)
0 commit comments