From 293cbbb3bc39e6103211b9c20a6e38a8f3704b3f Mon Sep 17 00:00:00 2001 From: Radhi Fadlillah Date: Mon, 28 May 2018 20:22:42 +0700 Subject: [PATCH] Add mutex to prevent race --- cmd/cmd-handler.go | 7 ++++++- cmd/serve/web-handler-api.go | 7 ++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/cmd/cmd-handler.go b/cmd/cmd-handler.go index 65b1b38..718bc61 100644 --- a/cmd/cmd-handler.go +++ b/cmd/cmd-handler.go @@ -264,7 +264,8 @@ func (h *cmdHandler) updateBookmarks(cmd *cobra.Command, args []string) { } } - // Prepare wait group + // Prepare wait group and mutex + mx := sync.Mutex{} wg := sync.WaitGroup{} // Fetch bookmarks from database @@ -291,6 +292,7 @@ func (h *cmdHandler) updateBookmarks(cmd *cobra.Command, args []string) { wg.Add(1) go func(pos int, book model.Bookmark) { + // Make sure to increase bar defer func() { bar.Incr() wg.Done() @@ -331,7 +333,10 @@ func (h *cmdHandler) updateBookmarks(cmd *cobra.Command, args []string) { book.ImageURL = fmt.Sprintf("/thumb/%d", book.ID) } + // Update list of bookmarks + mx.Lock() bookmarks[pos] = book + mx.Unlock() }(i, book) } diff --git a/cmd/serve/web-handler-api.go b/cmd/serve/web-handler-api.go index 28cece9..902a655 100644 --- a/cmd/serve/web-handler-api.go +++ b/cmd/serve/web-handler-api.go @@ -309,7 +309,8 @@ func (h *webHandler) apiUpdateCache(w http.ResponseWriter, r *http.Request, ps h err = json.NewDecoder(r.Body).Decode(&ids) checkError(err) - // Prepare wait group + // Prepare wait group and mutex + mx := sync.Mutex{} wg := sync.WaitGroup{} // Fetch bookmarks from database @@ -321,6 +322,7 @@ func (h *webHandler) apiUpdateCache(w http.ResponseWriter, r *http.Request, ps h wg.Add(1) go func(pos int, book model.Bookmark) { + // Make sure to stop wait group defer wg.Done() // Parse URL @@ -359,7 +361,10 @@ func (h *webHandler) apiUpdateCache(w http.ResponseWriter, r *http.Request, ps h book.ImageURL = fmt.Sprintf("/thumb/%d", book.ID) } + // Update list of bookmarks + mx.Lock() books[pos] = book + mx.Unlock() }(i, book) }