【问题标题】:Weird channel behavior in gogo中奇怪的通道行为
【发布时间】:2016-10-06 08:20:26
【问题描述】:
package main
import (
    "encoding/json"
    "fmt"
    "/something/models"
    "os"
    "path/filepath"
    "runtime"
)

func WriteDeviceToFile(d chan *models.Device, fileName string) {

_, b, _, _ := runtime.Caller(0)
basepath := filepath.Dir(b)
filePath := basepath + "/dataFile/" + fileName

var f *os.File
var err error


f, _ = os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0600)

defer f.Close()


for device := range d {
    deviceB, err := json.Marshal(device)
    fmt.Println(string(deviceB))
    if err == nil {
        if _, err = f.WriteString(string(deviceB)); err != nil {
            panic(err)
        }
    } else {
        panic(err)
    }
}

}

func main() {
deviceChan := make(chan *models.Device)
go WriteDeviceToFile(deviceChan, "notalive.txt")
d := models.NewDevice("12346", "")
deviceChan <- d
d = models.NewDevice("abcd", "")
deviceChan <- d
close(deviceChan)
}

这仅适用于发送到频道的至少两个设备。在 deviceChan 中只有一个设备时,该函数不会接收任何内容。通道在 WriteDeviceToFile 到达之前就消失了吗?

【问题讨论】:

  • main返回时程序退出。没有什么能阻止main 在文件写入之前退出。
  • 这似乎是原因。谢谢。我现在觉得有点傻。你想把它作为答案让我接受吗?

标签: go channel


【解决方案1】:

main 返回时程序退出。没有什么可以阻止main 在文件写入之前退出

【讨论】:

    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 2021-11-05
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    相关资源
    最近更新 更多