Похожие чаты

In the link above, Search() will start a goroutine like

this:
res := make(chan []string)
go func() {
res <- slowSearch(from, to)
close(res)
}()
and in next step, it will wait for cahnnels in a select:
// wait for 2 events: either of one will be the result
for {
select {
case dst := <-res:
return dst, nil
case <-ctx.Done():
return []string{}, ctx.Err()
}
}

So when <-ctx.Done() going to have any message, it will return our function return []string{}, ctx.Err().

My question is: after canceling the context and return from Search, the main problem is our goroutine is still running in the background!
for example, the slowSearch() takes 17 seconds to write result into our res channel. and our context timeout is (for example) 3 seconds.
Now after Search() reaching the timeout, our context will be canceled, and Search() will be returned.
But slowSearch() still running in backgroun for 17 seconds!

What should we do in this case?

7 ответов

10 просмотров

Pass the parent context to slow search, there you also listen for its cancellation, that way it won't have to stay around doing nothing!

there’s no way to kill a goroutine, so you must write slowSearch in such a way that it respects a cancalable context. slowSearch must check whether the context was canceled and return ASAP

Daddy- Автор вопроса
Roman Sharkov
there’s no way to kill a goroutine, so you must wr...

slowSearch() can do one thing at same time Either wait for context to be canceled, or doing its own job! My problem is here

Daddy
slowSearch() can do one thing at same time Either ...

why can’t you make it check the context?

Daddy- Автор вопроса

Похожие вопросы

Обсуждают сегодня

Какой-то там пердун в 90-х решил, что есть какая-то разная типизация. Кого вообще это волнует?
КТ315
49
Hi. Do we have a raid bot? Why nobody doing raids on X? Even RH mentioned this and nobody paying attention...whats the channel for hex memes? If mods cant run raids just insta...
H
31
Подскажите, а есть vault lite или ченить такое?) А то нужен вольт для похода в вольт, но весит он ~500 мб) как-то многовато для парочки запросов ))
Alexandr Orloff
17
блеать, почему так?? где в роутере это исправляется?
Арсен Маньяков 🇦🇲
16
void terminal_scroll() { memmove(terminal_buffer, terminal_buffer + VGA_WIDTH, buffer_size - VGA_WIDTH); memset(terminal_buffer + buffer_size - VGA_WIDTH, 0, VGA_WIDTH); ...
Егор
47
🌊 Ocean Nodes Dashboard Update 🚀 Hey, Oceaners! First off, a massive round of applause 👏to all of you for the amazing engagement since we launched Ocean Nodes. In just a few ...
KreigDK | Never DM first🌊
3
Всем привет! Подскажите, пожалуйста, в чем ошибка? Настраиваю подключение к MySQL. Либы лежат рядом с exe. Все как по "учебнику"
Евгений
16
А можете как-то проверить меня по знаниям по ассемблеру?
A A
132
Здравствуйте! У меня появилась возможность купить книгу "Изучай Haskell во имя добра!". Но я где-то слышал, что эта книга устарела. Насколько это правда??
E
22
люди, которые используют flameshot, к вам вопрос. Можно-ли поставить хоткей на создание скриншота? В программе есть отдел "горячие клавиши", но там все для редактирования, скр...
ThunDer104
11
Карта сайта