ctx_mutex.go 359 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
package internal

import (
	"context"
)

type CtxMutex chan struct{}

func NewCtxMutex() CtxMutex {
	return make(CtxMutex, 1)
}

func (m CtxMutex) Lock(ctx context.Context) error {
	select {
	case m <- struct{}{}:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

func (m CtxMutex) Unlock() {
	select {
	case <-m:
	default:
		panic("not locked")
	}
}