Skip to content

Commit

Permalink
feat: add SetSafety to set multiply times
Browse files Browse the repository at this point in the history
  • Loading branch information
jizhuozhi committed Sep 5, 2024
1 parent e028ae9 commit b9b5395
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
14 changes: 10 additions & 4 deletions future.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ type Future[T any] struct {
state *state[T]
}

func (s *state[T]) set(val T, err error) {
func (s *state[T]) set(val T, err error) bool {
for {
st := atomic.LoadUint64(&s.state)
if !isFree(st) {
panic("promise already satisfied")
return false
}
if atomic.CompareAndSwapUint64(&s.state, st, st+stateDelta) {
s.val = val
Expand All @@ -69,7 +69,7 @@ func (s *state[T]) set(val T, err error) {
head.next = nil
}
}
return
return true
}
}
}
Expand Down Expand Up @@ -135,7 +135,13 @@ func NewPromise[T any]() *Promise[T] {
}

func (p *Promise[T]) Set(val T, err error) {
p.state.set(val, err)
if !p.state.set(val, err) {
panic("promise already satisfied")
}
}

func (p *Promise[T]) SetSafety(val T, err error) bool {
return p.state.set(val, err)
}

func (p *Promise[T]) Future() *Future[T] {
Expand Down
10 changes: 10 additions & 0 deletions future_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,16 @@ func TestPromiseSetTwice(t *testing.T) {
})
}

func TestPromiseSetSafetyTwice(t *testing.T) {
p := NewPromise[int]()
f := p.Future()
p.SetSafety(1, nil)
p.SetSafety(2, nil)
val, err := f.Get()
assert.Equal(t, 1, val)
assert.NoError(t, err)
}

func TestFutureSubscribe(t *testing.T) {
p := NewPromise[int]()
f := p.Future()
Expand Down

0 comments on commit b9b5395

Please sign in to comment.