Last active
May 8, 2020 19:54
-
-
Save ankur22/7ceedcb518182aca89f01f2691e6c78c to your computer and use it in GitHub Desktop.
Using timer to identify slow writes to a channel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
eg.Go(func() error { | |
defer close(lines) | |
for { | |
if !scanner.Scan() { | |
fmt.Println("Reader: Completed") | |
break | |
} | |
lines <- scanner.Text() | |
time.Sleep(time.Second) // To fake the slow writing to the lines channel | |
select { | |
case <-ctx.Done(): | |
fmt.Println("Reader: Context closed") | |
return ctx.Err() | |
default: | |
} | |
} | |
if err := scanner.Err(); err != nil { | |
return fmt.Errorf("reader error - %w", err) | |
} | |
return nil | |
}) | |
eg.Go(func() error { | |
for { | |
select { | |
case <-ctx.Done(): | |
fmt.Println("Sender: Context closed") | |
return ctx.Err() | |
case <-time.NewTimer(time.Millisecond * 500).C: | |
fmt.Println("Sender: Write to channel is taking sometime") | |
case l, ok := <-lines: | |
if !ok { | |
fmt.Printf("Sender: Channel closed\n", l) | |
return nil | |
} | |
fmt.Printf("Sender: Sending %s to remote database\n", l) | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment