我正在构建一个状态栏应用程序,其中栏显示了当前专注的窗口的标题。条栏每秒更新(在无限循环中)。因此,由于主循环卡在睡眠函数上,因此窗口焦点变化不会立即反映在栏中。

我正在对窗口管理器的(sway) IPC插座进行轮询,以改变Goroutine的窗口焦点。但是,如何从窗口标题更改的Goroutine "inform" "inform"?

主要循环看起来像这样:

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是我制作的公用事业库。
注2:这是我第一次使用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:
      }
  }