Skip to content

Commit 2e9f17b

Browse files
committed
fix: avoid racy use of atomic counter
Don't know what I was smoking in 08f4ce1 ("fix: use C11 atomic functions for concurrent counter updates", 2024-08-17), but I had concurrent threads doing this: | Thread A | Thread B | | ------------- | ------------- | | Read counter | Read counter | | Write counter | Write counter |
1 parent 822b868 commit 2e9f17b

File tree

1 file changed

+4
-8
lines changed

1 file changed

+4
-8
lines changed

lua/wincent/commandt/lib/matcher.c

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -190,12 +190,10 @@ result_t *commandt_matcher_run(matcher_t *matcher, const char *needle) {
190190
if (i == worker_count - 1) {
191191
// For the last worker, we'll just use the main thread.
192192
heap_t *heap = get_matches(&worker_args[i]);
193+
unsigned offset = atomic_fetch_add(&matches_count, heap->count);
193194
memcpy(
194-
matches + atomic_load(&matches_count),
195-
heap->entries,
196-
heap->count * sizeof(haystack_t *)
195+
matches + offset, heap->entries, heap->count * sizeof(haystack_t *)
197196
);
198-
atomic_fetch_add(&matches_count, heap->count);
199197
heap_free(heap);
200198
} else {
201199
int err = pthread_create(
@@ -213,12 +211,10 @@ result_t *commandt_matcher_run(matcher_t *matcher, const char *needle) {
213211
if (err != 0) {
214212
die("phtread_join() failed", err);
215213
}
214+
unsigned offset = atomic_fetch_add(&matches_count, heap->count);
216215
memcpy(
217-
matches + atomic_load(&matches_count),
218-
heap->entries,
219-
heap->count * sizeof(haystack_t *)
216+
matches + offset, heap->entries, heap->count * sizeof(haystack_t *)
220217
);
221-
atomic_fetch_add(&matches_count, heap->count);
222218
heap_free(heap);
223219
}
224220

0 commit comments

Comments
 (0)