Skip to content

Commit

Permalink
Lesson 23
Browse files Browse the repository at this point in the history
  • Loading branch information
Satan3 committed Apr 22, 2022
1 parent e0abfba commit 643f67c
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lesson23/info.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Context:
a) Хранить значения
b) Сообщать о завершении

1. Background, TODO
2. With value
3. With cancel
4. With deadline/timeout

5. Worker pool
96 changes: 96 additions & 0 deletions lesson23/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package main

import (
"context"
"fmt"
"runtime"
"sync"
"time"
)

func main() {
//baseKnowledge()
workerPool()
}

func baseKnowledge() {
ctx := context.Background()
fmt.Println(ctx)

toDo := context.TODO()
fmt.Println(toDo)

withValue := context.WithValue(ctx, "name", "vasya")
fmt.Println(withValue.Value("name"))

withCancel, cancel := context.WithCancel(ctx)
fmt.Println(withCancel.Err())
cancel()
fmt.Println(withCancel.Err())

withDeadline, cancel := context.WithDeadline(ctx, time.Now().Add(time.Second*3))
defer cancel()
fmt.Println(withDeadline.Deadline())
fmt.Println(withDeadline.Err())
fmt.Println(<-withDeadline.Done())

withTimeout, cancel := context.WithTimeout(ctx, time.Second*2)
defer cancel()
fmt.Println(withTimeout.Done())
}

func workerPool() {

ctx, cancel := context.WithCancel(context.Background())
ctx, cancel = context.WithTimeout(context.Background(), time.Millisecond*20)
defer cancel()

wg := &sync.WaitGroup{}
numbersToProcess, processedNumbers := make(chan int, 5), make(chan int, 5)

for i := 0; i <= runtime.NumCPU(); i++ {
wg.Add(1)
go func() {
defer wg.Done()
worker(ctx, numbersToProcess, processedNumbers)
}()
}

go func() {
for i := 0; i < 1000; i++ {
/*if i == 500 {
cancel()
}*/
numbersToProcess <- i
}
close(numbersToProcess)
}()

go func() {
wg.Wait()
close(processedNumbers)
}()

var counter int
for resultValue := range processedNumbers {
counter++
fmt.Println(resultValue)
}

fmt.Println(counter)
}

func worker(ctx context.Context, toProcess <-chan int, processed chan<- int) {
for {
select {
case <-ctx.Done():
return
case value, ok := <-toProcess:
if !ok {
return
}
time.Sleep(time.Millisecond)
processed <- value * value
}
}
}

0 comments on commit 643f67c

Please sign in to comment.