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

A Telegram spokesman declined to comment on the bond issue or the amount of the debt the company has due. The spokesman said Telegram’s equipment and bandwidth costs are growing because it has consistently posted more than 40% year-to-year growth in users.

The global forecast for the Asian markets is murky following recent volatility, with crude oil prices providing support in what has been an otherwise tough month. The European markets were down and the U.S. bourses were mixed and flat and the Asian markets figure to split the difference.The TSE finished modestly lower on Friday following losses from the financial shares and property stocks.For the day, the index sank 15.09 points or 0.49 percent to finish at 3,061.35 after trading between 3,057.84 and 3,089.78. Volume was 1.39 billion shares worth 1.30 billion Singapore dollars. There were 285 decliners and 184 gainers.

telegram from it


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