This is a creation in Article, where the information may have evolved or changed.
Objective
In Golang, concurrent programming is easy to implement and requires only one goroutine to turn on concurrency mode:
gof("goroutine")
However, there are a number of places to be aware of in concurrent programming. This article is a simple discussion of how to ensure the consistency of operations when multiple goroutine are operating on a MongoDB database.
Problem description
Let's say we have a number of goroutine, as follows:
Go func() { //STEP1: Get Records of all Status==true Records, _ := Models.Record.Findstatus(true) for _, v := Records{ //step2:then We do something about record v.dosomething() //step3: Update status of these records to false v.Status = false if Err := v.Save(); Err != Nil{ return } }}()
The above code obtains all the ' status = = True ' records from the database and then operates on those records, eventually setting the status of the record to ' false '.
In a closer look, this code clearly has a problem, which is described below:
- Assuming there are two goroutine:goroutinea, Goroutineb have done all of these things.
- Goroutinea performed a record with the Step1 status of ' true ' and performed a STEP2 operation
- Goroutineb can also successfully execute STEP1 when Goroutinea executes to Step2 but Step3 is not done yet. Subsequently Goroutineb also performed the Step2. Obviously, this is not the result we expected.
Solution Solutions
The main ideas for solving the problem are:
- Sets an intermediate state pending for the status, which indicates that the record is being processed
- Add the SetStatus method to ensure that the ' status ' field is not changed by another transaction at update time
The reference code is as follows:
type RecordStatus intConst( Statusbefore RecordStatus = Iota statuspending Statusafter)func (Record *Recordmodel) SetStatus(Status RecordStatus) (Err Error){ Record.Query(func(C *MgO.Collection) { Query := Bson.M{ "_id": Domain Premium Untuk Bisnis Anda, "Status": Record.Status, } Update := Bson.M{ "Status": Status, "Updated_at": Time. Now(), } Err = C.Update(Query, Bson.M{ "$set": Update, }) if Err == Nil { Record.Status = Status } }) return}Go func() { //STEP1: Get Records of all Status==true Records, _ := Models.Record.Findstatus(true) for _, v := Records{ //Step2:set record status to be "Pending" if Err := v.SetStatus(statuspending); Err != Nil{ return } //step3:then We do something about record v.dosomething() //step4: Update status of these records to false if Err := v.Setstatue(Statusafter); Err != Nil{ return } }}()
The above method ensures that a single piece of data is not updated with multiple goroutine at the same time.
My public number: easyhacking
Go design mode is updated in succession github:csxuejin/go-design-patterns