2 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊
在這里簡(jiǎn)化邏輯的一種方法可能是運(yùn)行一個(gè)修改地圖的 goroutine。然后,它可以監(jiān)聽(tīng)通道上的新值(因?yàn)槿绻错樞蛱幚碇祽?yīng)該沒(méi)問(wèn)題)。您需要小心知道您的 goroutine 何時(shí)返回以確保它不會(huì)泄漏。一般來(lái)說(shuō),你不應(yīng)該在 goroutines 之間共享數(shù)據(jù),你應(yīng)該使用通道在 goroutines 之間進(jìn)行通信。
這是一個(gè)示例,說(shuō)明如何使用通道而不是共享內(nèi)存(游樂(lè)場(chǎng)版本)來(lái)實(shí)現(xiàn)此類應(yīng)用程序。
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貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
我認(rèn)為您在設(shè)置此類跟蹤器時(shí)需要設(shè)置標(biāo)志,一個(gè)用于價(jià)值上升,另一個(gè)用于價(jià)值下降。我實(shí)施了一個(gè)
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當(dāng)值超過(guò)設(shè)置的閾值時(shí),作為 go 例程運(yùn)行并打印到控制臺(tái)。我認(rèn)為這就是您正在尋找的功能,這里缺少的是Last.Store我認(rèn)為是您的代碼自定義的功能。我相信還有其他方法可以處理這個(gè)問(wèn)題。這對(duì)我來(lái)說(shuō)似乎很簡(jiǎn)單。
- 2 回答
- 0 關(guān)注
- 171 瀏覽
添加回答
舉報(bào)