Why fmt inside a goroutine doesn't print anything out?

agolangf · · 619 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>This is the code</p> <pre><code>package main import ( &#34;encoding/json&#34; &#34;fmt&#34; &#34;io/ioutil&#34; &#34;log&#34; &#34;os&#34; &#34;time&#34; &#34;github.com/lucavallin/yfirbord-grovepi/pkg/connections&#34; &#34;github.com/lucavallin/yfirbord-grovepi/pkg/io&#34; &#34;github.com/lucavallin/yfirbord-grovepi/pkg/sensors&#34; &#34;github.com/lucavallin/yfirbord-grovepi/pkg/sensors/parsers&#34; ) const ( grovePiAddress = 0x04 secondsWait = 360 ) // config should have pinNumber -&gt; sensors, in a way that sensors are mapped to pins var loadedSensors map[string][]sensors.Sensor func main() { // Load sensors config, err := ioutil.ReadFile(&#34;./sensors.json&#34;) if err != nil { fmt.Printf(&#34;Sensors configuration file not found.\nERROR: %s \n&#34;, err) os.Exit(1) } if json.Unmarshal(config, &amp;loadedSensors); err != nil { fmt.Printf(&#34;Sensors configuration is invalid.\nERROR: %s \n&#34;, err) os.Exit(1) } // Init GrovePi on address g, err := connections.NewGrovePi(grovePiAddress) if err != nil { fmt.Printf(&#34;Couldn&#39;t create connection with device.\nERROR: %s \n&#34;, err) os.Exit(1) } defer g.Close() // Create readers reader := io.NewReader(parsers.GetParsers(), g) // Create channel c := make(chan parsers.Measurement) // Start reading! for _, sensor := range loadedSensors[&#34;input&#34;] { // Go read the sensor every 5 minutes go func(r *io.Reader, s sensors.Sensor, c chan&lt;- parsers.Measurement) { for { measurement, err := r.Read(s) if err != nil { log.Panicln(err) } else { c &lt;- measurement } // Read every secondsWait minutes time.Sleep(time.Second * secondsWait) } }(reader, sensor, c) } // Create API manager // Print out go func(c chan parsers.Measurement) { measurement := &lt;-c for item, measure := range measurement { fmt.Printf(&#34;%s: %v\n&#34;, item, measure) } }(c) time.Sleep(time.Minute) } </code></pre> <p>Nothing is printed :|</p> <hr/>**评论:**<br/><br/>JHunz: <pre><p>If that&#39;s your whole code, your problem is probably that there&#39;s nothing blocking in the main thread. Goroutines terminate when the main thread does, which it will because it has nothing to do after launching the goroutines.</p></pre>theGeekPirate: <pre><p><a href="https://youtu.be/f6kdp27TYZs?t=456" rel="nofollow">This</a> will explain everything.</p> <p>main() does not wait for all goroutines to finish before exiting the program.</p></pre>epiris: <pre><p>You might find sync.errgroup useful for waiting for your goroutines to finish. It&#39;s essentially a more convenient WaitGroup.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

619 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传