我正在构建一个状态栏应用程序,其中状态栏显示当前聚焦窗口的标题。该栏每秒更新一次(无限循环)。因此,窗口焦点的变化不会立即反映在栏中,因为主循环停留在睡眠功能上。
我正在轮询窗口管理器(sway)的 IPC 套接字,以了解 Goroutine 中窗口焦点的变化。但是我如何从 goroutine 中“通知”主循环窗口标题已更改?
主循环如下所示:
func main(){
title_queue := make(chan string)
go poll_changes(title_queue)
var title string = get_title()
for {
current_time := get_time()
update_status_bar(title, current_time)
time.Sleep(time.Duration(time.Second))
title = <-title_queue // But sleep is blocking this
// channel may also block the main loop now
}
}
poll_changes 看起来像这样:
func poll_changes(title chan string) {
var addr string = swayipc.Getaddr()
var conn net.Conn = swayipc.Getsock(addr)
var events []string = []string{"window"}
swayipc.Subscribe(conn, events) // subscribe to window change events
var result map[string]interface{}
for {
response := swayipc.Unpack(conn)
json.Unmarshal(response, &result)
if result["change"] == "focus" {
window, _ := result["container"].(map[string]interface{})
title <- window["name"].(string) // how to inform the main loop of this variable change?
}
}
}
注1:
swayipc
是我制作的实用程序库。Go
来构建任何类型的软件。我之前在 python
中构建了这个确切的东西,其中我使用了 threading.Event
。但我不知道该怎么做。如果您认为我的解决方案存在根本问题,请指出。
使用股票代码:
tick:=time.Ticker(time.Second)
defer tick.Stop()
title:="title"
for {
select {
case <-tick.T:
current_time := get_time()
update_status_bar(title, current_time)
case title=<-title_queue:
}
}