There are several useful ways to use synchronous locking (e.g. mentioning @Tudor). But I want to warn about one thing: synchronization is not blocked.
You may have, for example, an integer supported by comparison and exchange, and thatโs fine. You may also have a queue supported by non-blocking algorithms (this is a bit complicated, but there are good algorithms for this), and the queue is also fine.
But if you try to use a counter to count the items in the queue, you will get the wrong answers. There will be times when an item has been added, but the counter does not yet reflect it (or vice versa), and you may get errors if you trust it (for example, you can try adding to the full queue).
In short, you can have every element that matches itself, but does not match each other.
source share