roylee0704 / gron

gron, Cron Jobs in Go.
MIT License
1.03k stars 62 forks source link

Data race in Add method #3

Open pravj opened 7 years ago

pravj commented 7 years ago

Using channel based synchronization in Add method prevents the data races when the cron instance is running.

Although, it can't stop them when the cron instance is inactive.

package main

import (
  "fmt"
  "time"
  "github.com/roylee0704/gron"
)

func main() {
  blocker := make(chan int)
  g := gron.New()

  g.AddFunc(gron.Every(4*time.Second), func() {
    fmt.Println("J-1/4")
  })
  g.AddFunc(gron.Every(3*time.Second), func() {
    fmt.Println("J-2/3")
  })

  // this will access (write) the shared state 'entries' concurrently
  go func() {
    g.AddFunc(gron.Every(2*time.Second), func() {
      fmt.Println("J-3/2")
    })
  }()

  g.Start()

  <-blocker
}

Running this with Golang's Race Detector will report the data race.

$ go run -race main.go

I propose to use Mutex for this particular case.

cc @roylee0704