Skip to content

Data race in Add method #3

@pravj

Description

@pravj

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions