How to lock a co-program by Go (no new one is allowed)

< H2 > problem description < / H2 >

1. Maybe my title description is not very clear, here is a detailed description

The

project is developed in beego, where there is another method in the controller

//
func (this *ApiController) SyncImages() {
.
.
.
go models.TestSyncImages(images)
.
.
.
}

there are methods called by the above co-program in another models package

func TestSyncImages(list []SyncImage) {
    var image = auxpi.Image{}
    var wg sync.WaitGroup
    for _, value := range list {
        go func(url string, id uint) {
            wg.Add(1)
            defer wg.Done()
            res, _ := http.Get(url)
            lUrl, name, del := localStoreInfo(res.Header.Get("Content-Type"), url)
            dst, _ := os.Create(name)
            io.Copy(dst, res.Body)
            image.ID = id
            image.Url = lUrl
            image.Delete = del
            AddSyncImage(image)
            
        }(value.External, value.ImageID)
    }
    wg.Wait()

}

Workflow is:

commands for users to submit synchronize pictures -> Controller receives data SyncImages () method-> SyncImages () enable cooperative procedure to execute TestSyncImages () method

but now there is a problem. If the user clicks two or more times at the same time, he will repeatedly enter TestSyncImages () , which will disrupt the current work. If he clicks several times, it will even cause a memory overflow.

I would like to ask you, how to ensure that the TestSyncImages () method will not be executed multiple times, is there any way to lock this thing, or use other better methods to solve it?


I think what you need is singleton mode. Take a look at this article .


in the SyncImages method, I suggest you use user ID to add cache judgment. For example, if you can only click once a minute, check whether the cache exists. If so, it is not synchronized. If not, synchronize after writing to the cache


if it is a stand-alone program, it is recommended to use sync.Once. If it is a distributed server, it is recommended to use the setnx instruction of redis. Add a lock. You can search Baidu and refer to similar articles such as https://www.jianshu.com/p/c97...

.
Menu