Add mutex to prevent race

This commit is contained in:
Radhi Fadlillah 2018-05-28 20:22:42 +07:00
parent a74773bd14
commit 293cbbb3bc
2 changed files with 12 additions and 2 deletions

View file

@ -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)
}

View file

@ -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)
}