File tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "errors"
5
+ "fmt"
6
+ "log"
7
+ "sync"
8
+ )
9
+
10
+ type Stack struct {
11
+ lock sync.Mutex // concurrency-safe stack
12
+ stack []int
13
+ }
14
+
15
+ func New () * Stack {
16
+ return & Stack {
17
+ lock : sync.Mutex {},
18
+ stack : make ([]int , 0 ),
19
+ }
20
+ }
21
+
22
+ func (s * Stack ) Push (n int ) {
23
+ s .lock .Lock ()
24
+ defer s .lock .Unlock ()
25
+ s .stack = append (s .stack , n )
26
+ fmt .Printf ("pushed %v to the stack \n " , n )
27
+ }
28
+
29
+ func (s * Stack ) Pop () (int , error ) {
30
+ s .lock .Lock ()
31
+ defer s .lock .Unlock ()
32
+
33
+ length := len (s .stack )
34
+ if length == 0 {
35
+ err := errors .New ("stack is empty" )
36
+ return 0 , err
37
+ }
38
+
39
+ // extract the last item in stack
40
+ last := s .stack [length - 1 ]
41
+
42
+ // remove the last item in stack
43
+ s .stack = s .stack [:length - 1 ]
44
+
45
+ fmt .Printf ("removed %v from the stack \n " , last )
46
+ return last , nil
47
+ }
48
+
49
+ func main () {
50
+ stack := New ()
51
+ wg := sync.WaitGroup {}
52
+ concurrency := 3
53
+
54
+ // concurrently push values to the stack
55
+ wg .Add (concurrency )
56
+ for i := 0 ; i < concurrency ; i ++ {
57
+ go func (n int ) {
58
+ stack .Push (n + 10 )
59
+ wg .Done ()
60
+ }(i )
61
+ }
62
+
63
+ // sequentially pop value off the stack
64
+ wg .Wait ()
65
+ for j := 0 ; j < 3 ; j ++ {
66
+ _ , err := stack .Pop ()
67
+ if err != nil {
68
+ log .Fatal (err )
69
+ }
70
+ }
71
+ }
You can’t perform that action at this time.
0 commit comments