Skip to content

Commit c2631ba

Browse files
committed
Added goroutines and channels and buffered channels in the goroutines module
1 parent 7446935 commit c2631ba

File tree

5 files changed

+72
-0
lines changed

5 files changed

+72
-0
lines changed

go_basics/go.work

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use (
77
./defer_panic_recover
88
./functions
99
./gomaps
10+
./goroutines
1011
./interfaces
1112
./loops
1213
./methods

go_basics/goroutines/channels/go.mod

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

go_basics/goroutines/channels/main.go

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func sum(nums []int, c chan int) {
6+
length := len(nums)
7+
sum := 0
8+
for i := 0; i < length; i++ {
9+
sum += nums[i]
10+
}
11+
12+
fmt.Println("Sending to channel")
13+
c <- sum
14+
}
15+
16+
func main() {
17+
18+
nums := []int{
19+
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
20+
}
21+
22+
c := make(chan int)
23+
24+
// this helps goroutines to sync
25+
go sum(nums[:len(nums)/2], c)
26+
go sum(nums[len(nums)/2:], c)
27+
28+
firstSum, secondSum := <-c, <-c
29+
30+
fmt.Printf("The first sum = %d \n The second sum = %d \n", firstSum, secondSum)
31+
32+
// buffered channels
33+
34+
var channel_v1 chan int = make(chan int, 2)
35+
36+
channel_v1 <- 1
37+
channel_v1 <- 2
38+
39+
fmt.Println("first", <-channel_v1)
40+
fmt.Println("second", <-channel_v1)
41+
}

go_basics/goroutines/go.mod

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

go_basics/goroutines/goroutines.go

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"time"
6+
)
7+
8+
func saySomething(text string) {
9+
10+
for i := 0; i < 5; i++ {
11+
time.Sleep(100 * time.Millisecond)
12+
fmt.Printf("%s \n", text)
13+
}
14+
15+
}
16+
17+
func main() {
18+
19+
// side villans
20+
go saySomething("Meeta is cute")
21+
22+
// main villan
23+
saySomething("When you run it what will happen?")
24+
}

0 commit comments

Comments
 (0)