How do library functions that accept a context implement context cancellation inside?

77 views
Skip to first unread message

Gurunandan Bhat

unread,
Jul 21, 2023, 3:11:58 AM7/21/23
to golang-nuts
Hi, 

Are there any common patterns that standard and 3rd party library functions use to implement cancelling a context passed to it? I have looked at the source of exec.CommandContext and it starts the process and spawns a goroutine that kills the process when ctx.Done() is closed. That looks simple enough. 

It seems to me that the key to implementing cancellation enabled function is to look at specific points inside the function where ctx.Done() is checked for. As an example, if I want to create a cancellable function that reads lines from a file, would select'ing on ctx.Done() be a good place?

Thanks. 

Gurunandan Bhat

unread,
Jul 21, 2023, 3:21:15 AM7/21/23
to golang-nuts
Sorry - I meant ..."calling select once per line...." be a good point

Tamás Gulácsi

unread,
Jul 21, 2023, 8:11:20 AM7/21/23
to golang-nuts
It depends. Checking the context (btw "if err := ctx.Err(); err != nil { return err }" is enough, no need for "select")
is cheap but not free. So partition for reasonable sized chunks of work.

Tamás
Reply all
Reply to author
Forward
0 new messages