package main
import (
"fmt"
"time"
)
// Resource represents the entity to be monitored
type Resource struct {
ID string
Value int
}
// Watcher watches for changes in resources
type Watcher struct {
resources map[string]*Resource
onChange func(resource *Resource)
}
// NewWatcher creates a new watcher
func NewWatcher(onChange func(resource *Resource)) *Watcher {
return &Watcher{
resources: make(map[string]*Resource),
onChange: onChange,
}
}
// UpdateResource updates the resource and triggers the event
func (w *Watcher) UpdateResource(resource *Resource) {
w.resources[resource.ID] = resource
w.onChange(resource)
}
func main() {
watcher := NewWatcher(func(resource *Resource) {
fmt.Printf("Resource updated: ID=%s, Value=%d\n", resource.ID, resource.Value)
})
go func() {
for {
time.Sleep(2 * time.Second)
watcher.UpdateResource(&Resource{ID: "1", Value: newValue()})
}
}()
select {} // Keep the main routine alive
}
func newValue() int {
return int(time.Now().UnixNano() % 100) // Mock value generation
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?