Sunnee
Sunnee

Reputation: 3

When using the global gorm.DB to create data in multiple goroutine, the data is overwritten partly

Env

go version 1.18

gorm v1.25.2

Code

My code in goroutine:

type TaskThread struct {
    task       *model.Task
    jobID      uint64
}

func (t *TaskThread) Start() {
    go t.run()
}

func (t *TaskThread) run() {
    // ...
    t.task.JobID = t.jobID
    log.Info(fmt.Sprintf("[GenDebug]Before save task: %+v", *t.task))
    err := model.AddTask(t.task)
    if err != nil {
        // handle error
    }
    log.Info(fmt.Sprintf("[GenDebug]After save task: %+v", *t.task))
    // ...
}

My code with global gorm.DB:

func AddTask(task *Task) error {
    // var globalDB *gorm.DB
    // globalDB is a global variable. I initialized it using the officially recommended connection pool.(sql.DB)
    result := globalDB.Create(task)
    if result.Error != nil {
        return result.Error
    }
    return nil
}

Log:

msg="[GenDebug]Before save task: {ID:0 JobID:5512 ScenarioName:20241015103655-20241015103725}"
msg="[GenDebug]Before save task: {ID:0 JobID:5513 ScenarioName:20241004120645-20241004120715}"
msg="[GenDebug]After save task: {ID:547019 JobID:5513 ScenarioName:20241004120645-20241004120715}"
msg="[GenDebug]After save task: {ID:547020 JobID:5512 ScenarioName:20241004120645-20241004120715}"

Question

1. Am I doing something wrong with gorouting and usage of the global gorm thread pool object?

As the log output shows, the data ScenarioName in MySQL has been covered.

2. Why does partial coverage of data occur?

I did not add a unique index with JobID in my table.

Upvotes: 0

Views: 15

Answers (0)

Related Questions