CodeBlanks Logo Icon CodeBlanks

Summary - Select

Combine select, timeout and close to write a scheduler.

Summary - Select

In this section you learned select:

  • Wait on many channels with select and fair picking
  • Non-blocking with default for event loops
  • Timeout with time.After to prevent forever waits
  • Close a channel with close and end range

Now you will combine these to write a scheduler: select, timeout and close together.

Practice Write a scheduler

Inside main, add a select { case ... default: ... } block and print scheduler with fmt.Println.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    ch := make(chan string)
    select {
    case m := <-ch:
        fmt.Println(m)
    default:
        fmt.Println("zamanlayıcı")
    }
}

Expected output

zamanlayıcı

Practice Scheduler output

Inside main, print select scheduler with fmt.Println.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    fmt.Println("select scheduler")
}

Expected output

select scheduler

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 select usage

Question
select {
case v := <-ch:
    fmt.Println(v)
____:
    fmt.Println("zaman aşımı")
}
Answer
select {
case v := <-ch:
    fmt.Println(v)
case <-time.After(1e9):
    fmt.Println("zaman aşımı")
}

Explanation: time.After returns a channel; case waits on it.

2 Match section concepts

Term Meaning
select Multi-wait
default Non-blocking
time.After Timeout
close Close

All lessons in Intermediate