Telegram Group & Telegram Channel
🔄 Cascading Context Cancellation в Go: от исходников к продакшену

В статье подробно разобрано, как Go управляет цепочками отмен Context — от базового кода до продакшен-паттернов.

🧠 Как устроена отмена Context внутри Go

1. При создании cancelCtx функция propagateCancel делает так, чтобы отмена родителя передавалась детям.
2. Если родитель — тоже cancelCtx, он хранит список потомков в children map и пробрасывает cancel(...) при отмене.
3. Если родитель имеет AfterFunc, используется таймер; иначе создаётся горутина, которая ждёт <-parent.Done() и вызывает cancel.

Структура cancelCtx:

type cancelCtx struct {
Context
mu sync.Mutex
done atomic.Value
children map[canceler]struct{}
err atomic.Value
cause error
}


🧪 WithCancelCause — отмена с причиной

Позволяет указывать причину отмены вместо обычного context.Canceled.
Пример:

ctx, cancel := context.WithCancelCause(base)
cancel(errors.New("my custom reason"))
fmt.Println(ctx.Err(), context.Cause(ctx))


Причина отмены наследуется дочерними контекстами.

🧵 Безопасность в многопоточности

Методы Done() и Err() потокобезопасны благодаря мьютексам и атомикам.
CancelFunc можно вызывать многократно — только первый вызов имеет эффект.

AfterFunc — код по отмене

Позволяет запускать функцию, когда контекст отменяется:

stop := context.AfterFunc(ctx, func() {
tx.Rollback()
})
...
if stop() { log.Println("cancel handler stopped") }


Если контекст уже отменён — функция вызовется немедленно. stop() может отменить выполнение функции.

🚫 WithoutCancel — фоновые задачи без отмены

Полезно, если горутина не должна завершаться при отмене родителя.
Важно: Done() == nil → чтение из канала блокирует навсегда.

⏲️ Таймеры: WithDeadline и WithTimeout

Функции создают контексты, которые отменяются автоматически по истечении времени.
Не забудьте делать defer cancel() после создания!

Практические советы


ctx, cancel := context.WithTimeout(parent, 100*time.Millisecond)
defer cancel()


Всегда вызывайте cancel() для освобождения ресурсов и предотвращения утечек.

🧰 Что в итоге

Этот материал охватывает:
• внутреннее устройство cancelCtx
• новые API: WithCancelCause, AfterFunc, WithoutCancel
• продакшен-паттерны безопасной отмены

📖 Полный текст статьи: https://dev.to/flew1x/cascading-context-cancellation-in-go-from-source-code-to-production-patterns-177j

@golang_books



tg-me.com/golang_books/1012
Create:
Last Update:

🔄 Cascading Context Cancellation в Go: от исходников к продакшену

В статье подробно разобрано, как Go управляет цепочками отмен Context — от базового кода до продакшен-паттернов.

🧠 Как устроена отмена Context внутри Go

1. При создании cancelCtx функция propagateCancel делает так, чтобы отмена родителя передавалась детям.
2. Если родитель — тоже cancelCtx, он хранит список потомков в children map и пробрасывает cancel(...) при отмене.
3. Если родитель имеет AfterFunc, используется таймер; иначе создаётся горутина, которая ждёт <-parent.Done() и вызывает cancel.

Структура cancelCtx:


type cancelCtx struct {
Context
mu sync.Mutex
done atomic.Value
children map[canceler]struct{}
err atomic.Value
cause error
}


🧪 WithCancelCause — отмена с причиной

Позволяет указывать причину отмены вместо обычного context.Canceled.
Пример:

ctx, cancel := context.WithCancelCause(base)
cancel(errors.New("my custom reason"))
fmt.Println(ctx.Err(), context.Cause(ctx))


Причина отмены наследуется дочерними контекстами.

🧵 Безопасность в многопоточности

Методы Done() и Err() потокобезопасны благодаря мьютексам и атомикам.
CancelFunc можно вызывать многократно — только первый вызов имеет эффект.

AfterFunc — код по отмене

Позволяет запускать функцию, когда контекст отменяется:

stop := context.AfterFunc(ctx, func() {
tx.Rollback()
})
...
if stop() { log.Println("cancel handler stopped") }


Если контекст уже отменён — функция вызовется немедленно. stop() может отменить выполнение функции.

🚫 WithoutCancel — фоновые задачи без отмены

Полезно, если горутина не должна завершаться при отмене родителя.
Важно: Done() == nil → чтение из канала блокирует навсегда.

⏲️ Таймеры: WithDeadline и WithTimeout

Функции создают контексты, которые отменяются автоматически по истечении времени.
Не забудьте делать defer cancel() после создания!

Практические советы


ctx, cancel := context.WithTimeout(parent, 100*time.Millisecond)
defer cancel()


Всегда вызывайте cancel() для освобождения ресурсов и предотвращения утечек.

🧰 Что в итоге

Этот материал охватывает:
• внутреннее устройство cancelCtx
• новые API: WithCancelCause, AfterFunc, WithoutCancel
• продакшен-паттерны безопасной отмены

📖 Полный текст статьи: https://dev.to/flew1x/cascading-context-cancellation-in-go-from-source-code-to-production-patterns-177j

@golang_books

BY Golang Books


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/golang_books/1012

View MORE
Open in Telegram


Golang Books Telegram | DID YOU KNOW?

Date: |

Can I mute a Telegram group?

In recent times, Telegram has gained a lot of popularity because of the controversy over WhatsApp’s new privacy policy. In January 2021, Telegram was the most downloaded app worldwide and crossed 500 million monthly active users. And with so many active users on the app, people might get messages in bulk from a group or a channel that can be a little irritating. So to get rid of the same, you can mute groups, chats, and channels on Telegram just like WhatsApp. You can mute notifications for one hour, eight hours, or two days, or you can disable notifications forever.

Pinterest (PINS) Stock Sinks As Market Gains

Pinterest (PINS) closed at $71.75 in the latest trading session, marking a -0.18% move from the prior day. This change lagged the S&P 500's daily gain of 0.1%. Meanwhile, the Dow gained 0.9%, and the Nasdaq, a tech-heavy index, lost 0.59%. Heading into today, shares of the digital pinboard and shopping tool company had lost 17.41% over the past month, lagging the Computer and Technology sector's loss of 5.38% and the S&P 500's gain of 0.71% in that time. Investors will be hoping for strength from PINS as it approaches its next earnings release. The company is expected to report EPS of $0.07, up 170% from the prior-year quarter. Our most recent consensus estimate is calling for quarterly revenue of $467.87 million, up 72.05% from the year-ago period.

Golang Books from us


Telegram Golang Books
FROM USA