Skip to content

Commit 6deb733

Browse files
committed
goroutine
1 parent e3c5ab9 commit 6deb733

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"time"
6+
)
7+
8+
func display(str string) {
9+
for i := 0; i < 5; i++ {
10+
// Uncomment to disable sleep in goroutine, we wouldn't see "Welcome", because it executes instantly
11+
time.Sleep(100 * time.Microsecond)
12+
13+
fmt.Println(str)
14+
}
15+
}
16+
17+
func main() {
18+
fmt.Println(time.Microsecond)
19+
// Calling Goroutine with `go` keyword
20+
go display("Welcome")
21+
22+
// Calling normal function
23+
display("Hello")
24+
25+
// Advangate of Goroutine
26+
// 1. cheaper than threads
27+
// 2. are stored in stack and its size can grow and shrink correspondingly, whereas stack of thread fixed.
28+
// 3. Goroutines can communicate using the channel and these channels are specially designed to prevent race conditions when accessing shared memory using Goroutines
29+
// 4. Suppose a program has one thread, and that thread has many Goroutines associated with it. If any of Goroutine blocks the thread due to resource requirement then all the remaining Goroutines will assign to a newly created OS thread. All these details are hidden from the programmers.
30+
31+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"time"
6+
)
7+
8+
// For goroutine 1
9+
func Aname() {
10+
11+
arr1 := [4]string{"Rohit", "Suman", "Aman", "Ria"}
12+
13+
for t1 := 0; t1 <= 3; t1++ {
14+
15+
time.Sleep(150 * time.Millisecond)
16+
fmt.Printf("%s\n", arr1[t1])
17+
}
18+
}
19+
20+
// For goroutine 2
21+
func Aid() {
22+
23+
arr2 := [4]int{300, 301, 302, 303}
24+
25+
for t2 := 0; t2 <= 3; t2++ {
26+
27+
time.Sleep(500 * time.Millisecond)
28+
fmt.Printf("%d\n", arr2[t2])
29+
}
30+
}
31+
32+
// Main function
33+
func main() {
34+
35+
fmt.Println("!...Main Go-routine Start...!")
36+
37+
// calling Goroutine 1
38+
go Aname()
39+
40+
// calling Goroutine 2
41+
go Aid()
42+
43+
// The output is fixed, see `two-goroutines.jpg` for the reason.
44+
time.Sleep(3500 * time.Millisecond)
45+
46+
// When sleep for 1800ms, not "303" output
47+
// time.Sleep(1800 * time.Millisecond)
48+
fmt.Println("\n!...Main Go-routine End...!")
49+
50+
}
56.5 KB
Loading

0 commit comments

Comments
 (0)