(注意社区版本已经多次更新,如下命令有过期)

调度模型

GPM的含义

  • G,表示一个 goroutine,即我需要分担出去的任务;
  • P,一个装满 G 的队列,用于维护一些任务;
  • M,一个操作器,用于将一个 G 搬到线程上执行;
  1. 创建一个 G 对象;
  2. 将 G 保存至 P中;
  3. P 去唤醒(告诉)一个 M,然后继续执行它的执行序(分配下一个 G);
  4. M 寻找空闲的 P,读取该 P 要分配的 G;
  5. 接下来 M 执行一个调度循环,调用 G → 执行 → 清理线程 → 继续找新的 G 执行。

常用命令

go modules

当modules功能启用时,依赖包的存放位置变更为$GOPATH/pkg,允许同一个package多个版本并存,且多个项目可以共享缓存的 module。

go mod xxx:

  • download download modules to local cache(下载依赖包)

  • edit edit go.mod from tools or scripts(编辑go.mod

  • graph print module requirement graph (打印模块依赖图)

  • init initialize new module in current directory(在当前目录初始化mod)

  • tidy add missing and remove unused modules(拉取缺少的模块,移除不用的模块)

  • vendor make vendored copy of dependencies(将依赖复制到vendor下)

  • verify verify dependencies have expected content (验证依赖是否正确)

why explain why packages or modules are needed(解释为什么需要依赖)

使用

go mod init:自成生成go.mod,其他命令也会自动维护该脚本。 go run xxx 会自动查找并添加依赖 go get xxx 升级依赖包版本