Skip to content

Commit

Permalink
Add mutex to prevent race
Browse files Browse the repository at this point in the history
  • Loading branch information
RadhiFadlillah committed May 28, 2018
1 parent a74773b commit 293cbbb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
7 changes: 6 additions & 1 deletion cmd/cmd-handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()
Expand Down Expand Up @@ -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)
}

Expand Down
7 changes: 6 additions & 1 deletion cmd/serve/web-handler-api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
}

Expand Down

0 comments on commit 293cbbb

Please sign in to comment.