is it possible to encourage threads to line up without forcing it?

Viewed 69

I have a single atomic variable that multiple threads are loading, they perform some local calculations on it, then call an atomically fetch_and on it. They check that they were able to make there change before another thread did, if not, repeat using the updated value returned from fetch_and

Works a lot faster than a locked version. But would be nice if I could encourage multiple threads to align and not load the atomic number until fetch_and completes without forcing it.

Is this possible? Thinking it might be using a memory fence or two?

1 Answers

There's no point. If two threads don't try to do this at the same time, they'll make perfect progress. If two threads do try to do this at the same time, one of them will have to wait in some way. What way that other thread waits has no effect on performance.

If each thread needs about the same amount of time between accesses to the atomic variable, they'll line up naturally because they'll proceed past the first such access one at a time. If threads need different amounts of time, no attempt to line them up could possibly succeed. The only way to keep two threads from arriving at the same time is to slow one of them down and the consequence of them arriving at the same time is already that one of them slows down.

If the local calculations take so long that there's any risk that your code will spend a lot of time doing calculations that are thrown away, switch to using a lock.

Related