Skip to content

Commit

Permalink
[Allocator] add rw lock to support concurrency
Browse files Browse the repository at this point in the history
Signed-off-by: Bruce Ma <brucema19901024@gmail.com>
  • Loading branch information
mars1024 committed Sep 17, 2019
1 parent b697ddf commit 81a12c7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
28 changes: 23 additions & 5 deletions allocator.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@

package allocator

import "errors"
import (
"errors"
"sync"
)

type Interface interface {
Assign(RangeID) error
Expand All @@ -32,22 +35,27 @@ var (
)

type allocator struct {
*sync.RWMutex
ranger Range
store map[RangeID]struct{}
}

func NewAllocator(ranger Range) Interface {
return &allocator{
ranger: ranger,
store: make(map[RangeID]struct{}),
RWMutex: new(sync.RWMutex),
ranger: ranger,
store: make(map[RangeID]struct{}),
}
}

func (a *allocator) Assign(id RangeID) error {
if ! a.ranger.Contains(id) {
a.Lock()
defer a.Unlock()

if !a.ranger.Contains(id) {
return ErrOutOfRange
}
if a.Has(id) {
if a.has(id) {
return ErrAllocated
}
a.store[id] = struct{}{}
Expand All @@ -65,11 +73,21 @@ func (a *allocator) Allocate() (RangeID, interface{}, error) {
}

func (a *allocator) Release(id RangeID) error {
a.Lock()
defer a.Unlock()

delete(a.store, id)
return nil
}

func (a *allocator) Has(id RangeID) bool {
a.RLock()
defer a.RUnlock()

return a.has(id)
}

func (a *allocator) has(id RangeID) bool {
if _, exist := a.store[id]; exist {
return true
}
Expand Down
4 changes: 2 additions & 2 deletions allocators/port/allocator.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ package port

import "github.com/mars1024/allocator"

func NewPortAllocator(lowerPort , upperPort int) (allocator.Interface, error) {
func NewPortAllocator(lowerPort, upperPort int) (allocator.Interface, error) {
ranger, err := NewPortRanger(lowerPort, upperPort)
if err != nil{
if err != nil {
return nil, err
}

Expand Down

0 comments on commit 81a12c7

Please sign in to comment.