一尘不染

go中奇怪的频道行为

go

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到达之前消失了吗?


阅读 164

收藏
2020-07-02

共1个答案

一尘不染

main返回时程序退出。main写入文件之前没有任何阻止

2020-07-02