Weird channel behavior in go

送分小仙女□ 提交于 2019-12-12 04:28:05

问题


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)
}

This only works with at least two devices sent to channel. With only one device in deviceChan, the function does not receive anything. Is the channel gone before the WriteDeviceToFile gets to it?


回答1:


The program exits when main returns. Nothing prevents main from exiting before the files are written



来源:https://stackoverflow.com/questions/39885585/weird-channel-behavior-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!