change cache

This commit is contained in:
yourok
2019-09-23 09:25:32 +03:00
parent 8933a860a0
commit 2b286c15c1
14 changed files with 194 additions and 678 deletions

View File

@@ -1,9 +1,9 @@
package memcache
import (
"fmt"
"sync"
"log"
"server/utils"
)
@@ -14,42 +14,62 @@ type buffer struct {
}
type BufferPool struct {
buffs map[int]*buffer
bufferLength int64
bufferCount int
mu sync.Mutex
buffs map[int]*buffer
frees int
size int64
mu sync.Mutex
}
func NewBufferPool(bufferLength int64) *BufferPool {
func NewBufferPool(bufferLength int64, capacity int64) *BufferPool {
bp := new(BufferPool)
bp.bufferLength = bufferLength
bp.buffs = make(map[int]*buffer)
buffsSize := int(capacity/bufferLength) + 3
bp.frees = buffsSize
bp.size = bufferLength
return bp
}
func (b *BufferPool) mkBuffs() {
if b.buffs != nil {
return
}
b.buffs = make(map[int]*buffer, b.frees)
log.Println("Create", b.frees, "buffers")
for i := 0; i < b.frees; i++ {
buf := buffer{
-1,
make([]byte, b.size, b.size),
false,
}
b.buffs[i] = &buf
}
}
func (b *BufferPool) GetBuffer(p *Piece) (buff []byte, index int) {
b.mu.Lock()
defer b.mu.Unlock()
b.mkBuffs()
for id, buf := range b.buffs {
if !buf.used {
fmt.Println("Get buffer:", id)
buf.used = true
buf.pieceId = p.Id
buff = buf.buf
index = id
b.frees--
//fmt.Printf("Get buffer: %v %v %v %p\n", id, p.Id, b.frees, buff)
return
}
}
log.Println("Create slow buffer")
fmt.Println("Create buffer:", b.bufferCount)
buf := new(buffer)
buf.buf = make([]byte, b.bufferLength)
buf.used = true
buf.pieceId = p.Id
b.buffs[b.bufferCount] = buf
index = b.bufferCount
buf := buffer{
p.Id,
make([]byte, b.size, b.size),
true,
}
b.frees++
b.buffs[b.frees] = &buf
buff = buf.buf
b.bufferCount++
index = b.frees
return
}
@@ -60,10 +80,11 @@ func (b *BufferPool) ReleaseBuffer(index int) {
}
b.mu.Lock()
defer b.mu.Unlock()
b.mkBuffs()
if buff, ok := b.buffs[index]; ok {
fmt.Println("Release buffer:", index)
buff.used = false
buff.pieceId = -1
b.frees++
} else {
utils.FreeOSMem()
}
@@ -72,6 +93,9 @@ func (b *BufferPool) ReleaseBuffer(index int) {
func (b *BufferPool) Used() map[int]struct{} {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.buffs) == 0 {
b.mkBuffs()
}
used := make(map[int]struct{})
for _, b := range b.buffs {
if b.used {
@@ -82,13 +106,5 @@ func (b *BufferPool) Used() map[int]struct{} {
}
func (b *BufferPool) Len() int {
b.mu.Lock()
defer b.mu.Unlock()
count := 0
for _, b := range b.buffs {
if b.used {
count++
}
}
return count
return b.frees
}