无法循环遍历动态通道的问题。

huangapple go评论88阅读模式
英文:

Unable to loop through golang dynamic channels

问题

我想循环遍历菜单选项。然而,它在第一个选项处停止,因为没有带有"default:"的选择是阻塞的,它不知道是否会动态出现更多选项。

下面是有问题的代码:

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"os/exec"
	"strings"
	"time"

	"github.com/getlantern/systray"
	"gopkg.in/yaml.v3"
)

var menuItensPtr []*systray.MenuItem
var config map[string]string
var commands []string

func main() {
	config = readconfig()
	systray.Run(onReady, onExit)
}

func onReady() {
	systray.SetIcon(getIcon("assets/menu.ico"))
	menuItensPtr = make([]*systray.MenuItem, 0)
	commands = make([]string, 0)
	for k, v := range config {
		menuItemPtr := systray.AddMenuItem(k, k)
		menuItensPtr = append(menuItensPtr, menuItemPtr)
		commands = append(commands, v)
   }
   systray.AddSeparator()
	// mQuit := systray.AddMenuItem("Quit", "Quits this app")
	go func() {
		for {
			systray.SetTitle("My tray menu")
			systray.SetTooltip("https://github.com/evandrojr/my-tray-menu")
			time.Sleep(1 * time.Second)
		}
	}()

	go func() {
		for{
			for i, menuItenPtr := range menuItensPtr {
				

          select { 
/// EXECUTION GETS STUCK HERE!!!!!!!
				case<-menuItenPtr.ClickedCh:
					execute(commands[i])
				}
			}	
			// select {
			// case <-mQuit.ClickedCh:
			// 	systray.Quit()
			// 	return
			// // default:
			// }
		}
	}()
}

func onExit() {
	// Cleaning stuff will go here. 
}

func getIcon(s string) []byte {
	b, err := ioutil.ReadFile(s)
	if err != nil {
		fmt.Print(err)
	}
	return b
}

func execute(commands string){
	command_array:= strings.Split(commands, " ")
	command:=""
	command, command_array = command_array[0], command_array[1:]
	cmd := exec.Command(command, command_array ...)
    var out bytes.Buffer
    cmd.Stdout = &out
    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
    // fmt.Printf("Output %s\n", out.String())
}

func readconfig()  map[string]string{
	yfile, err := ioutil.ReadFile("my-tray-menu.yaml")
	if err != nil {
		 log.Fatal(err)
	}
	data := make(map[string]string)
	err2 := yaml.Unmarshal(yfile, &data)
	if err2 != nil {
		 log.Fatal(err2)
	}
	for k, v := range data {
		 fmt.Printf("%s -> %s\n", k, v)
	}
	return data
}


下面是可行的临时解决方法:

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"

	"github.com/getlantern/systray"
	"gopkg.in/yaml.v3"
)

var menuItensPtr []*systray.MenuItem
var config map[string]string
var commands []string
var labels []string
var programPath string

func main() {
	setProgramPath()
	config = readconfig()
	time.Sleep(1 * time.Second)
	systray.Run(onReady, onExit)
}

func onReady() {
	systray.SetIcon(getIcon(filepath.Join(programPath,"assets/menu.ico")))
	menuItensPtr = make([]*systray.MenuItem, 0)
	i := 0
	op0 := systray.AddMenuItem(labels[i], commands[i])
	i++
	op1 := systray.AddMenuItem(labels[i], commands[i])
	i++
	op2 := systray.AddMenuItem(labels[i], commands[i])
	i++
	op3 := systray.AddMenuItem(labels[i], commands[i])
	i++

	systray.AddSeparator()
	mQuit := systray.AddMenuItem("Quit", "Quits this app")
	go func() {
		for {
			systray.SetTitle("My tray menu")
			systray.SetTooltip("https://github.com/evandrojr/my-tray-menu")
			time.Sleep(1 * time.Second)
		}
	}()

	go func() {
		for {
			select {
// HERE DOES NOT GET STUCK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			case <-op0.ClickedCh:
				execute(commands[0])
			case <-op1.ClickedCh:
				execute(commands[1])
			case <-op2.ClickedCh:
				execute(commands[2])
			case <-op3.ClickedCh:
				execute(commands[3])
			case <-mQuit.ClickedCh:
				systray.Quit()
				return
			}
		}
	}()
}

func onExit() {
	// Cleaning stuff will go here.
}

func getIcon(s string) []byte {
	b, err := ioutil.ReadFile(s)
	if err != nil {
		fmt.Print(err)
	}
	return b
}

func setProgramPath(){
	ex, err := os.Executable()
    if err != nil {
        panic(err)
    }
    programPath = filepath.Dir(ex)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

func execute(commands string) {
	command_array := strings.Split(commands, " ")
	command := ""
	command, command_array = command_array[0], command_array[1:]
	cmd := exec.Command(command, command_array...)
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Output %s\n", out.String())
}

func readconfig() map[string]string {
	yfile, err := ioutil.ReadFile(filepath.Join(programPath,"my-tray-menu.yaml"))
	if err != nil {
		log.Fatal(err)
	}

	data := make(map[string]string)
	err2 := yaml.Unmarshal(yfile, &data)
	if err2 != nil {
		log.Fatal(err2)
	}

	labels = make([]string, 0)
	commands = make([]string, 0)

	for k, v := range data {
		labels = append(labels, k)
		commands = append(commands, v)
		fmt.Printf("%s -> %s\n", k, v)
	}
	fmt.Print(len(labels))
	return data
}

完整的源代码在这里:
https://github.com/evandrojr/my-tray-menu

英文:

I want to loop through the menu's options. However, it stops at the first option, since the select without "default:" is blocking and it does not know more options will appear dynamically.

Bellow is the broken code:

package main
import (
&quot;bytes&quot;
&quot;fmt&quot;
&quot;io/ioutil&quot;
&quot;log&quot;
&quot;os/exec&quot;
&quot;strings&quot;
&quot;time&quot;
&quot;github.com/getlantern/systray&quot;
&quot;gopkg.in/yaml.v3&quot;
)
var menuItensPtr []*systray.MenuItem
var config map[string]string
var commands []string
func main() {
config = readconfig()
systray.Run(onReady, onExit)
}
func onReady() {
systray.SetIcon(getIcon(&quot;assets/menu.ico&quot;))
menuItensPtr = make([]*systray.MenuItem,0)
commands = make([]string,0)
for k, v := range config {
menuItemPtr := systray.AddMenuItem(k, k)
menuItensPtr = append(menuItensPtr, menuItemPtr)
commands = append(commands, v)
}
systray.AddSeparator()
// mQuit := systray.AddMenuItem(&quot;Quit&quot;, &quot;Quits this app&quot;)
go func() {
for {
systray.SetTitle(&quot;My tray menu&quot;)
systray.SetTooltip(&quot;https://github.com/evandrojr/my-tray-menu&quot;)
time.Sleep(1 * time.Second)
}
}()
go func() {
for{
for i, menuItenPtr := range menuItensPtr {
select { 
/// EXECUTION GETS STUCK HERE!!!!!!!
case&lt;-menuItenPtr.ClickedCh:
execute(commands[i])
}
}	
// select {
// case &lt;-mQuit.ClickedCh:
// 	systray.Quit()
// 	return
// // default:
// }
}
}()
}
func onExit() {
// Cleaning stuff will go here. 
}
func getIcon(s string) []byte {
b, err := ioutil.ReadFile(s)
if err != nil {
fmt.Print(err)
}
return b
}
func execute(commands string){
command_array:= strings.Split(commands, &quot; &quot;)
command:=&quot;&quot; 
command, command_array = command_array[0], command_array[1:]
cmd := exec.Command(command, command_array ...)
var out bytes.Buffer
cmd.Stdout = &amp;out
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
// fmt.Printf(&quot;Output %s\n&quot;, out.String())
}
func readconfig()  map[string]string{
yfile, err := ioutil.ReadFile(&quot;my-tray-menu.yaml&quot;)
if err != nil {
log.Fatal(err)
}
data := make(map[string]string)
err2 := yaml.Unmarshal(yfile, &amp;data)
if err2 != nil {
log.Fatal(err2)
}
for k, v := range data {
fmt.Printf(&quot;%s -&gt; %s\n&quot;, k, v)
}
return data
}

Bellow is the ugly workaround that works:

package main
import (
&quot;bytes&quot;
&quot;fmt&quot;
&quot;io/ioutil&quot;
&quot;log&quot;
&quot;os&quot;
&quot;os/exec&quot;
&quot;path/filepath&quot;
&quot;strings&quot;
&quot;time&quot;
&quot;github.com/getlantern/systray&quot;
&quot;gopkg.in/yaml.v3&quot;
)
var menuItensPtr []*systray.MenuItem
var config map[string]string
var commands []string
var labels []string
var programPath string
func main() {
setProgramPath()
config = readconfig()
time.Sleep(1 * time.Second)
systray.Run(onReady, onExit)
}
func onReady() {
systray.SetIcon(getIcon(filepath.Join(programPath,&quot;assets/menu.ico&quot;)))
menuItensPtr = make([]*systray.MenuItem, 0)
i := 0
op0 := systray.AddMenuItem(labels[i], commands[i])
i++
op1 := systray.AddMenuItem(labels[i], commands[i])
i++
op2 := systray.AddMenuItem(labels[i], commands[i])
i++
op3 := systray.AddMenuItem(labels[i], commands[i])
i++
systray.AddSeparator()
mQuit := systray.AddMenuItem(&quot;Quit&quot;, &quot;Quits this app&quot;)
go func() {
for {
systray.SetTitle(&quot;My tray menu&quot;)
systray.SetTooltip(&quot;https://github.com/evandrojr/my-tray-menu&quot;)
time.Sleep(1 * time.Second)
}
}()
go func() {
for {
select {
// HERE DOES NOT GET STUCK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
case &lt;-op0.ClickedCh:
execute(commands[0])
case &lt;-op1.ClickedCh:
execute(commands[1])
case &lt;-op2.ClickedCh:
execute(commands[2])
case &lt;-op3.ClickedCh:
execute(commands[3])
case &lt;-mQuit.ClickedCh:
systray.Quit()
return
}
}
}()
}
func onExit() {
// Cleaning stuff will go here.
}
func getIcon(s string) []byte {
b, err := ioutil.ReadFile(s)
if err != nil {
fmt.Print(err)
}
return b
}
func setProgramPath(){
ex, err := os.Executable()
if err != nil {
panic(err)
}
programPath = filepath.Dir(ex)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func execute(commands string) {
command_array := strings.Split(commands, &quot; &quot;)
command := &quot;&quot;
command, command_array = command_array[0], command_array[1:]
cmd := exec.Command(command, command_array...)
var out bytes.Buffer
cmd.Stdout = &amp;out
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf(&quot;Output %s\n&quot;, out.String())
}
func readconfig() map[string]string {
yfile, err := ioutil.ReadFile(filepath.Join(programPath,&quot;my-tray-menu.yaml&quot;))
if err != nil {
log.Fatal(err)
}
data := make(map[string]string)
err2 := yaml.Unmarshal(yfile, &amp;data)
if err2 != nil {
log.Fatal(err2)
}
labels = make([]string, 0)
commands = make([]string, 0)
for k, v := range data {
labels = append(labels, k)
commands = append(commands, v)
fmt.Printf(&quot;%s -&gt; %s\n&quot;, k, v)
}
fmt.Print(len(labels))
return data
}

Full source code here:
https://github.com/evandrojr/my-tray-menu

答案1

得分: 1

select 语句用于“选择一组可能的发送或接收操作中的哪一个将继续进行”。规范说明了如何进行选择:

>如果有一个或多个通信可以继续进行,将通过均匀伪随机选择来选择一个可以继续进行的通信。否则,如果存在默认情况,则选择该情况。如果没有默认情况,则“select”语句将阻塞,直到至少有一个通信可以继续进行。

你的工作示例:

select {
    case &lt;-op0.ClickedCh:
        execute(commands[0])
    case &lt;-op1.ClickedCh:
        execute(commands[1])
    // ...
}

成功地使用 select 来在提供的选项之间进行选择。然而,如果你只传递一个选项,例如:

select { 
    case&lt;-menuItenPtr.ClickedCh:
        execute(commands[i])
    }
}  

select 语句将阻塞,直到 &lt;-menuItenPtr.ClickedCh 准备就绪(例如,接收到了某些内容)。这实际上与不使用 select 是一样的:

&lt;-menuItenPtr.ClickedCh:
execute(commands[i])

你期望的结果可以通过提供一个默认选项来实现:

select { 
    case&lt;-menuItenPtr.ClickedCh:
        execute(commands[i])
    }
    default:
}  

根据上面规范中的引用,如果其他选项都无法继续进行,将选择 default 选项。虽然这可能会起作用,但并不是一个很好的解决方案,因为你实际上得到了:

for {
   // 检查事件是否发生(非阻塞)
}

这将不必要地占用 CPU 时间,因为它不断循环检查事件。一个更好的解决方案是启动一个 goroutine 来监视每个通道:

for i, menuItenPtr := range menuItensPtr {
    go func(c chan struct{}, cmd string) {
        for range c { execute(cmd) }
    }(menuItenPtr.ClickedCh, commands[i])
}
// 启动另一个 goroutine 来处理退出

上述方法可能会起作用,但可能会导致 execute 并发调用(如果你的代码不是线程安全的,可能会引发问题)。解决这个问题的一种方法是使用“扇入”模式(由 @kostix 提出,并在 Rob Pike 视频 中由 @John 提到):

cmdChan := make(chan int)

for i, menuItenPtr := range menuItensPtr {
    go func(c chan struct{}, cmd string) {
        for range c { cmdChan &lt;- cmd }
    }(menuItenPtr.ClickedCh, commands[i])
}

go func() {
    for {
        select { 
            case cmd := &lt;- cmdChan:
                execute(cmd) // 处理命令        
           case &lt;-mQuit.ClickedCh:
                systray.Quit()
                return
        }
    }
}()

注意:上面的所有代码直接输入到问题中,请将其视为伪代码!

英文:

select "chooses which of a set of possible send or receive operations will proceed". The spec sets out how this choice is made:

>If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.

Your working example:

select {
case &lt;-op0.ClickedCh:
execute(commands[0])
case &lt;-op1.ClickedCh:
execute(commands[1])
// ...
}

uses select successfully to choose between one of the offered options. However if you pass a single option e.g.

select { 
    case&lt;-menuItenPtr.ClickedCh:
        execute(commands[i])
    }
}  

The select will block until &lt;-menuItenPtr.ClickedCh is ready to proceed (e.g. something is received). This is effectively the same as not using a select:

&lt;-menuItenPtr.ClickedCh:
execute(commands[i])

The result you were expecting can be achieved by providing a default option:

select { 
    case&lt;-menuItenPtr.ClickedCh:
        execute(commands[i])
    }
    default:
}  

As per the quote from the spec above the default option will be chosen if none of the other options can proceed. While this may work it's not a very good solution because you effectively end up with:

for {
// Check if event happened (not blocking)           
}

This will tie up CPU time unnecessarily as it continually loops checking for events. A better solution would be to start a goroutine to monitor each channel:

for i, menuItenPtr := range menuItensPtr {
    go func(c chan struct{}, cmd string) {
        for range c { execute(cmd) }
    }(menuItenPtr.ClickedCh, commands[i])
}
// Start another goroutine to handle quit

The above will probably work but does lead to the possibility that execute will be called concurrently (which might cause issues if your code is not threadsafe). One way around this is to use the "fan in" pattern (as suggested by @kostix and in the Rob Pike video suggested by @John); something like:

cmdChan := make(chan int)

for i, menuItenPtr := range menuItensPtr {
    go func(c chan struct{}, cmd string) {
        for range c { cmdChan &lt;- cmd }
    }(menuItenPtr.ClickedCh, commands[i])
}

go func() {
    for {
        select { 
            case cmd := &lt;- cmdChan:
                execute(cmd) // Handle command        
           case &lt;-mQuit.ClickedCh:
                systray.Quit()
                return
        }
    }
}()

note: all code above entered directly into the question so please treat as pseudo code!

huangapple
  • 本文由 发表于 2022年8月7日 01:08:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/73261794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定