Telegram Group & Telegram Channel
🧠 Почему context.WithCancel может вызвать утечку goroutine

context.WithCancel — удобный способ завершать операции, но если не вызывать cancel(), вы получите утечку. Причём не всегда это очевидно.

Посмотрим:


func handler(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithCancel(r.Context())
// cancel не вызывается!
go doSomething(ctx)
w.Write([]byte("done"))
}

func doSomething(ctx context.Context) {
select {
case <-time.After(10 * time.Second):
fmt.Println("done work")
case <-ctx.Done():
fmt.Println("canceled")
}
}


Что здесь не так?

Если handler завершится раньше, чем doSomething, и cancel() не вызван — doSomething останется висеть, пока не истечёт r.Context() или time.After. И таких горутин может накопиться много, особенно при высоких нагрузках.

💡 Как избежать

1. Всегда вызывай cancel(), когда используешь context.WithCancel, даже если кажется, что это «не нужно».


ctx, cancel := context.WithCancel(r.Context())
defer cancel()


2. Если передаёшь контекст в goroutine — убедись, что она завершится, даже если вызывающая функция ушла.

context.WithCancel — мощный инструмент. Но без вызова cancel() ты легко создашь утечку, которую не поймаешь ни в логах, ни в профилях — только под нагрузкой.

👉 @golang_lib



tg-me.com/golang_lib/465
Create:
Last Update:

🧠 Почему context.WithCancel может вызвать утечку goroutine

context.WithCancel — удобный способ завершать операции, но если не вызывать cancel(), вы получите утечку. Причём не всегда это очевидно.

Посмотрим:


func handler(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithCancel(r.Context())
// cancel не вызывается!
go doSomething(ctx)
w.Write([]byte("done"))
}

func doSomething(ctx context.Context) {
select {
case <-time.After(10 * time.Second):
fmt.Println("done work")
case <-ctx.Done():
fmt.Println("canceled")
}
}


Что здесь не так?

Если handler завершится раньше, чем doSomething, и cancel() не вызван — doSomething останется висеть, пока не истечёт r.Context() или time.After. И таких горутин может накопиться много, особенно при высоких нагрузках.

💡 Как избежать

1. Всегда вызывай cancel(), когда используешь context.WithCancel, даже если кажется, что это «не нужно».


ctx, cancel := context.WithCancel(r.Context())
defer cancel()


2. Если передаёшь контекст в goroutine — убедись, что она завершится, даже если вызывающая функция ушла.

context.WithCancel — мощный инструмент. Но без вызова cancel() ты легко создашь утечку, которую не поймаешь ни в логах, ни в профилях — только под нагрузкой.

👉 @golang_lib

BY Библиотека Go (Golang) разработчика




Share with your friend now:
tg-me.com/golang_lib/465

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

What is Secret Chats of Telegram

Secret Chats are one of the service’s additional security features; it allows messages to be sent with client-to-client encryption. This setup means that, unlike regular messages, these secret messages can only be accessed from the device’s that initiated and accepted the chat. Additionally, Telegram notes that secret chats leave no trace on the company’s services and offer a self-destruct timer.

How To Find Channels On Telegram?

There are multiple ways you can search for Telegram channels. One of the methods is really logical and you should all know it by now. We’re talking about using Telegram’s native search option. Make sure to download Telegram from the official website or update it to the latest version, using this link. Once you’ve installed Telegram, you can simply open the app and use the search bar. Tap on the magnifier icon and search for a channel that might interest you (e.g. Marvel comics). Even though this is the easiest method for searching Telegram channels, it isn’t the best one. This method is limited because it shows you only a couple of results per search.

telegram from us


Telegram Библиотека Go (Golang) разработчика
FROM USA