5 Concurrency.1

This commit is contained in:
Aliberk Sandıkçı 2023-08-26 10:51:33 +03:00
parent d5ea5c3e46
commit 7098264e88
Signed by: asandikci
GPG key ID: 25C67A03B5666BC1
3 changed files with 106 additions and 0 deletions

24
5concurrency/channels.go Normal file
View file

@ -0,0 +1,24 @@
package main
import (
"fmt"
)
func hello(done chan int) {
fmt.Println("goroutine worked")
done <- 101101
}
func main() {
fmt.Println("Channels are a typed conduit through which you can send and receive values with the channel operator, <-")
myChannel1 := make(chan int)
fmt.Println("When data is sent to a channel, the control is blocked in the send statement until some other Goroutine reads from that channel")
fmt.Println("Similarly, when data is read from a channel, the read is blocked until some Goroutine writes data to that channel")
go hello(myChannel1)
fmt.Println(<-myChannel1)
fmt.Println("Calling channels causes main function wait to terminate")
fmt.Println("end of main function")
}

43
5concurrency/channels2.go Normal file
View file

@ -0,0 +1,43 @@
package main
import (
"fmt"
"time"
)
func producer(chnl chan int) {
for i := 0; i < 10; i++ {
time.Sleep(100 * time.Millisecond)
chnl <- i
}
close(chnl)
}
func outer(chn2 chan int) {
for i := 10; i < 100; i++ {
chn2 <- i
}
close(chn2)
}
func main() {
ch, ch2 := make(chan int), make(chan int)
go producer(ch)
go outer(ch2)
for {
v, ok := <-ch
if ok == false {
v, ok2 := <-ch2
if ok2 == false {
break
}
fmt.Println("Received2 ", v, ok)
continue
}
fmt.Println("Received ", v, ok)
}
ch3 := make(chan int)
go producer(ch3)
for v := range ch3 {
fmt.Println("Received ", v)
}
}

View file

@ -0,0 +1,39 @@
package main
import (
"fmt"
"time"
)
func printX() {
for i := 0; i < 100; i++ {
fmt.Print("X")
}
}
func printY() {
for i := 0; i < 100; i++ {
fmt.Print("Y")
}
}
func main() {
fmt.Println("a goroutine is a **lightweight** thread managed by the go runtime")
printX()
fmt.Println()
printY()
fmt.Println()
fmt.Println("you should see first X's then Y's")
time.Sleep(100 * time.Millisecond)
fmt.Println()
fmt.Println()
go printX()
go printY()
fmt.Println("you should see random X's and Y's, this because concurrency")
time.Sleep(1 * time.Second)
// wait for prevent main goroutine to terminate
}