Skip to content

Commit c34896a

Browse files
committed
Added concepts such as mutexes under go_basics/goroutines, added examples for trees to learn about channels. Finished close to every concept in go programming language :)
1 parent 9e0aa6b commit c34896a

File tree

6 files changed

+98
-0
lines changed

6 files changed

+98
-0
lines changed

go_basics/goroutines/mutexes/go.mod

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module anarchymonkey.com/go-basics/goroutines/mutexes
2+
3+
go 1.20

go_basics/goroutines/mutexes/go.sum

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
golang.org/x/tour v0.1.0 h1:OWzbINRoGf1wwBhKdFDpYwM88NM0d1SL/Nj6PagS6YE=
2+
golang.org/x/tour v0.1.0/go.mod h1:DUZC6G8mR1AXgXy73r8qt/G5RsefKIlSj6jBMc8b9Wc=
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math/rand"
6+
"sync"
7+
)
8+
9+
type Unique struct {
10+
mu sync.Mutex
11+
valueMapper map[int]int
12+
}
13+
14+
func (u *Unique) generateUniqueIdCollector(index int, wg *sync.WaitGroup) {
15+
defer wg.Done()
16+
fmt.Println("index is", index)
17+
u.mu.Lock()
18+
u.valueMapper[index] = int(rand.Intn(255))
19+
u.mu.Unlock()
20+
21+
}
22+
23+
func main() {
24+
25+
var uniq Unique = Unique{
26+
valueMapper: make(map[int]int),
27+
}
28+
29+
var wg sync.WaitGroup
30+
31+
for i := 0; i < 5; i++ {
32+
wg.Add(1)
33+
go uniq.generateUniqueIdCollector(i, &wg)
34+
}
35+
36+
wg.Wait()
37+
// time.Sleep(time.Second)
38+
fmt.Println(uniq.valueMapper)
39+
// wg.Done()
40+
}

go_basics/goroutines/trees/go.mod

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
module anarchymonkey.com/go-basics/goroutines/trees
2+
3+
go 1.20
4+
5+
require golang.org/x/tour v0.1.0

go_basics/goroutines/trees/go.sum

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
golang.org/x/tour v0.1.0 h1:OWzbINRoGf1wwBhKdFDpYwM88NM0d1SL/Nj6PagS6YE=
2+
golang.org/x/tour v0.1.0/go.mod h1:DUZC6G8mR1AXgXy73r8qt/G5RsefKIlSj6jBMc8b9Wc=

go_basics/goroutines/trees/trees.go

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
6+
"golang.org/x/tour/tree"
7+
)
8+
9+
func Walk(t *tree.Tree, ch chan int) {
10+
11+
if t == nil {
12+
return
13+
}
14+
15+
Walk(t.Left, ch)
16+
ch <- t.Value
17+
Walk(t.Right, ch)
18+
}
19+
20+
func Same(t1 *tree.Tree, t2 *tree.Tree) bool {
21+
22+
ch1, ch2 := make(chan int, 20), make(chan int, 20)
23+
24+
go Walk(t1, ch1)
25+
go Walk(t2, ch2)
26+
27+
for i := 0; i < 10; i++ {
28+
29+
v1, v2 := <-ch1, <-ch2
30+
31+
if v1 != v2 {
32+
return false
33+
}
34+
}
35+
36+
return true
37+
}
38+
39+
func main() {
40+
t1 := tree.New(1)
41+
42+
t2 := tree.New(1)
43+
44+
fmt.Println(Same(t1, t2))
45+
46+
}

0 commit comments

Comments
 (0)