Golang简单代码示例分享
Golang简单代码示例分享 大家好!我在GitHub上发布了一个新的代码(非常简单,是一个多线程的bash命令“包装器”)。如果这个简单的脚本能对你们有所帮助,我会非常高兴。链接:GitHub - JacobKatsman/bashwrapper: Bash wrapper on goland。谢谢。
1 回复
更多关于Golang简单代码示例分享的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
这是一个很实用的Go语言并发编程示例。让我分析一下这个bash包装器的核心实现:
// 主要结构体定义
type Command struct {
Cmd string
Args []string
}
// 并发执行多个命令的核心函数
func runCommands(commands []Command, maxConcurrent int) {
sem := make(chan struct{}, maxConcurrent) // 信号量控制并发数
var wg sync.WaitGroup
for _, cmd := range commands {
wg.Add(1)
go func(c Command) {
defer wg.Done()
sem <- struct{}{} // 获取信号量
defer func() { <-sem }() // 释放信号量
// 执行bash命令
execCmd := exec.Command(c.Cmd, c.Args...)
output, err := execCmd.CombinedOutput()
if err != nil {
fmt.Printf("Error executing %s: %v\n", c.Cmd, err)
}
fmt.Printf("Output for %s:\n%s\n", c.Cmd, output)
}(cmd)
}
wg.Wait()
}
这个实现展示了Go并发编程的几个关键特性:
- goroutine管理:使用
go关键字创建轻量级线程 - 并发控制:通过带缓冲的channel实现信号量模式
- 同步机制:
sync.WaitGroup确保所有goroutine完成 - 系统调用:
exec.Command执行外部命令
示例使用方式:
func main() {
commands := []Command{
{"ls", []string{"-la"}},
{"pwd", []string{}},
{"echo", []string{"Hello", "World"}},
}
// 最多同时执行2个命令
runCommands(commands, 2)
}
这个代码很好地体现了Go的并发哲学:通过channel和goroutine实现简洁高效的并发控制,避免了传统线程编程的复杂性。对于需要批量执行系统命令的场景,这种包装器非常实用。

