2 回答

TA貢獻1784條經驗 獲得超7個贊
在這里簡化邏輯的一種方法可能是運行一個修改地圖的 goroutine。然后,它可以監聽通道上的新值(因為如果按順序處理值應該沒問題)。您需要小心知道您的 goroutine 何時返回以確保它不會泄漏。一般來說,你不應該在 goroutines 之間共享數據,你應該使用通道在 goroutines 之間進行通信。
這是一個示例,說明如何使用通道而不是共享內存(游樂場版本)來實現此類應用程序。
package main
import (
? ? "fmt"
? ? "sync"
)
type value struct {
? ? key? ? ? ?string
? ? value? ? ?float64
? ? threshold float64
}
func main() {
? ? b := board{
? ? ? ? last: map[string]float64{},
? ? }
? ? c := b.start()
? ? wg := sync.WaitGroup{}
? ? for i := 0; i < 30; i++ {
? ? ? ? wg.Add(1)
? ? ? ? go func(i int) {
? ? ? ? ? ? for j := 15.0; j > 5; j-- {
? ? ? ? ? ? ? ? c <- value{"k1", j + float64(i+1)/100, 10}
? ? ? ? ? ? }
? ? ? ? ? ? wg.Done()
? ? ? ? }(i)
? ? }
? ? wg.Wait()
? ? close(c)
}
type board struct {
? ? last map[string]float64
}
func (b *board) start() chan<- value {
? ? c := make(chan value)
? ? go func() {
? ? ? ? for v := range c {
? ? ? ? ? ? b.notify(v)
? ? ? ? }
? ? }()
? ? return c
}
func (b *board) notify(v value) {
? ? if l, ok := b.last[v.key]; !ok || l >= v.threshold {
? ? ? ? if v.value < v.threshold {
? ? ? ? ? ? fmt.Printf("%s < %v (%v)\n", v.key, v.threshold, v.value)
? ? ? ? }
? ? }
? ? b.last[v.key] = v.value
}

TA貢獻1890條經驗 獲得超9個贊
我認為您在設置此類跟蹤器時需要設置標志,一個用于價值上升,另一個用于價值下降。我實施了一個
package main
import (
"fmt"
"sync"
)
const (
threshold int = 10
upperThreshold int = 20
)
var mu sync.Mutex
var downwatch bool
var upwatch bool
func main() {
var tracker int = 10
var temp int = 1
var sign int = 1
for i := 1; i < 20; i++ {
sign = sign * -1
temp = temp + i
go UpdateTracker(&tracker, temp*sign)
}
for {
}
return
}
func SetDownWatch() {
downwatch = true
}
func SetUpWatch() {
upwatch = true
}
func UnSetDownWatch() {
downwatch = false
}
func UnSetUpWatch() {
upwatch = false
}
func UpdateTracker(tracker *int, val int) {
mu.Lock()
defer mu.Unlock()
if !(upwatch || downwatch) {
if (*tracker)+val < threshold {
NotifyOnDrop()
SetDownWatch()
}
if (*tracker + val) > upperThreshold {
NotifyOnRise()
SetUpWatch()
}
}
if (*tracker)+val < threshold && upwatch {
NotifyOnDrop()
SetDownWatch()
UnSetUpWatch()
}
if (*tracker+val) > upperThreshold && downwatch {
NotifyOnRise()
SetUpWatch()
UnSetDownWatch()
}
*tracker = (*tracker) + val
fmt.Println((*tracker))
return
}
func NotifyOnDrop() {
fmt.Println("dropped")
return
}
func NotifyOnRise() {
fmt.Println("rose")
return
}
updateTracker當值超過設置的閾值時,作為 go 例程運行并打印到控制臺。我認為這就是您正在尋找的功能,這里缺少的是Last.Store我認為是您的代碼自定義的功能。我相信還有其他方法可以處理這個問題。這對我來說似乎很簡單。
- 2 回答
- 0 關注
- 181 瀏覽
添加回答
舉報