不知道為什么我的程式遇到錯誤
concurrent map iteration and map write
我已經把RLock()/mv.RUnlock()這里
for k := range confirmed_slot {
keys = append(keys, k)
}
這是我完整的測驗程式
package main
import (
"container/list"
"fmt"
"math/rand"
"sync"
"time"
"github.com/twotwotwo/sorts/sortutil"
)
var (
queue = list.New()
confirmed_slot = map[uint64]string{}
mv sync.RWMutex
)
func FetchConfirmedSlots() {
ticker := time.NewTicker(1 * time.Second)
for {
mv.RLock()
rand.Seed(time.Now().UnixNano())
r := randSeq(10)
slot := rand.Uint64()
confirmed_slot[slot] = r
queue.PushBack(slot)
fmt.Println("Slot Added " , slot , " ", len(confirmed_slot))
mv.RUnlock()
<-ticker.C
}
}
func RemoveItemSlotFull() {
ticker := time.NewTicker(1 * time.Millisecond)
for {
if queue.Len() == 150 {
mv.RLock()
front := queue.Front()
queue.Remove(front)
v, ok := front.Value.(uint64)
if ok {
fmt.Println("Slot deleted " , v)
delete(confirmed_slot, v)
fmt.Println("Slot deleted " , v , " ", len(confirmed_slot))
}
mv.RUnlock()
}
<-ticker.C
}
}
func GetLatestSlot() {
ticker := time.NewTicker(1 * time.Second)
for {
mv.RLock()
if queue.Len() >0 {
back := queue.Back()
fmt.Println("Slot Fetched ", back.Value , " ",len(confirmed_slot))
}
mv.RUnlock()
<-ticker.C
}
}
func GetConfirmedBlockHashes() {
ticker := time.NewTicker(1 * time.Second)
for {
if queue.Len() >0 {
mv.RLock()
back := queue.Back()
v, _ := back.Value.(uint64)
keys := make([]uint64, 0, len(confirmed_slot))
for k := range confirmed_slot {
keys = append(keys, k)
}
n := sortutil.SearchUint64s(keys,v)
fmt.Println("Found ... " , n, true)
mv.RUnlock()
}
<-ticker.C
}
}
func main() {
go FetchConfirmedSlots()
go RemoveItemSlotFull()
go GetLatestSlot()
go GetConfirmedBlockHashes()
select {}
}
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func randSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
uj5u.com熱心網友回復:
而不是mv.RLock()andmv.RUnlock()嘗試mv.Lock()and mv.Unlock()。您正在寫信給confirmed_slot.
Rlock()并且RUnlock()用于讀取 - 它們允許多個執行緒一次讀取,只要沒有寫入。
Lock()并且Unlock()將確保一次只有一個執行緒持有鎖,無論它是讀取還是寫入。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/438854.html
標籤:走
