sunty
2019-07-18 6a413e1d7d485f506e81c669bc692868c29cefb9
shardmap/shardmap.go
@@ -4,20 +4,18 @@
import (
   "sync"
    "fmt"
    "basic.com/pubsub/protomsg.git"
    //"encoding/json"
    //"fmt"
)
var commonmux sync.Mutex
const (
   DEF_SHARD_CNT = 32
   BKDR_SEED = 131 // 31 131 1313 13131 131313 etc...
)
type shardItem struct {
   sync.RWMutex
   data map[string]interface{}
}
@@ -28,15 +26,12 @@
var Count = make(chan int)
type wfOp func(a, b string) float32
type wfOp func(a []byte, b string) float32
/**
* @param uint8, shardCnt must be pow of two
*/
func New(shardCnt uint8) *ShardMap {
   if !isPowOfTwo(shardCnt) {
      shardCnt = DEF_SHARD_CNT
   }
   s := &ShardMap{
      shardCnt: shardCnt,
@@ -83,33 +78,58 @@
}
// modify by long.
func (s *ShardMap) Walk(wf wfOp, cfrom string) []protomsg.Baseinfo{
func (s *ShardMap) Walk(wf wfOp, cfrom []byte) ( map[string]float32 ){
    var wg sync.WaitGroup
    var second float32 
    var baseinfos []*protomsg.Baseinfo
    ids := make(map[string]float32)
   for _, si := range s.shards {
        var tempsi shardItem
            tempsi = *si
        wg.Add(1)
      go func(st *shardItem, fw wfOp, cf []byte) {
            defer wg.Done()
            commonmux.Lock()
         for id, feature := range st.data {
                 if str, ok := feature.(string); ok {
                    second = fw(cf,str)
                    if second == -1 {
                        continue
                     }
                    ids[id]=second
                 }
         }
       commonmux.Unlock()
      }(&tempsi, wf, cfrom)
   }
    wg.Wait()
    return ids
}
// print all
func (s *ShardMap) Printall() (infos []interface{}){
    var wg sync.WaitGroup
   for _, si := range s.shards {
        wg.Add(1)
      go func(s *shardItem, fw wfOp, cf string) {
      go func(s *shardItem) {
            defer wg.Done()
         s.RLock()
         for key, value := range s.data {
                 second = fw(cf,key)
                 if second == -1 {
                        continue
                 }
                 if info, ok := value.(*protomsg.Baseinfo) ;ok {
                    fmt.Println("比对分数: ", second)
                    info.CompareScore = second
                    baseinfos = append(baseinfos,info)
                 }
         }
         s.RUnlock()
      }(si,wf, cfrom)
         for _, value := range s.data {
                infos = append(infos, value)
            }
        s.RUnlock()
      }(si)
   }
    wg.Wait()
    return baseinfos
    return
}
func (s * ShardMap)GetLen() int {
@@ -124,10 +144,6 @@
   i := bkdrHash(key) & uint32(s.shardCnt-1)
   return s.shards[i]
}
func isPowOfTwo(x uint8) bool {
   return x != 0 && (x&(x-1) == 0)
}
//https://www.byvoid.com/blog/string-hash-compare/