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: |

How Does Telegram Make Money?

Telegram is a free app and runs on donations. According to a blog on the telegram: We believe in fast and secure messaging that is also 100% free. Pavel Durov, who shares our vision, supplied Telegram with a generous donation, so we have quite enough money for the time being. If Telegram runs out, we will introduce non-essential paid options to support the infrastructure and finance developer salaries. But making profits will never be an end-goal for Telegram.

Export WhatsApp stickers to Telegram on iPhone

You can’t. What you can do, though, is use WhatsApp’s and Telegram’s web platforms to transfer stickers. It’s easy, but might take a while.Open WhatsApp in your browser, find a sticker you like in a chat, and right-click on it to save it as an image. The file won’t be a picture, though—it’s a webpage and will have a .webp extension. Don’t be scared, this is the way. Repeat this step to save as many stickers as you want.Then, open Telegram in your browser and go into your Saved messages chat. Just as you’d share a file with a friend, click the Share file button on the bottom left of the chat window (it looks like a dog-eared paper), and select the .webp files you downloaded. Click Open and you’ll see your stickers in your Saved messages chat. This is now your sticker depository. To use them, forward them as you would a message from one chat to the other: by clicking or long-pressing on the sticker, and then choosing Forward.

telegram from ar


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