dqeonr8554 2018-07-06 14:52
浏览 57
已采纳

更改指向* os.File的指针

I have rotated files, and I need change files periodically, but I can't renew my pointer to file

var (
  file          *os.File
)

func init() {
    file, err = os.Create(fileName)
}

func main() {
  ticker = time.NewTicker(time.Second * 6)
  defer ticker.Stop()

  go func(file *os.File) {
      <- ticker.C
      fn := fmt.Sprintf("%d%s", time.Now().Unix(), ".txt")
      file, _ = os.Create(fn)
  }(file)

  http.HandleFunc("/go", goHandler)
}

func goHandler(w http.ResponseWriter, r *http.Request) {
  fmt.Printf("hand File: %v
", *file)
  // when handler triggered file stay the same
  file.WriteString(myPayload)
}

it changes inside goroutines, but it doesn't react in handler, so the file stays the same all time.

Suggest, pls, how I can change pointer to *os.File

  • 写回答

2条回答 默认 最新

  • douwengzao5790 2018-07-06 15:07
    关注

    In your code, the goroutine only runs once. So it creates a single new file and does nothing more - which means *file only changed once.

    You should change <- ticker.C to for _ = range ticker.C { ... }.

    And also, you should guard changing and reading values from *file with a sync.Mutex, because there is a data race between two goroutine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型