r/cpp • • May 22 '26

Building a Fast Lock-Free Queue in Modern C++ From Scratch

https://jaysmito.dev/blog/blog/04-fast-lockfree-queues/
135 Upvotes

29 comments sorted by

View all comments

72

u/woppo May 23 '26

You have a member function called IsEmpty: // This is an extremely handy function which we can add to the // Queue API so that we can use it to check if a queue is filled // or not and this will be very useful for a lot of situations // where you could technically put a thread to sleep based on // this value. bool IsEmpty(uint32_t threadId) { (void)threadId; std::unique_lock lock(m_Mutex); return m_Queue.empty(); }

It is not extremley handy. It should be called WasEmpty. It has no use whatsoever.

16

u/jetilovag May 23 '26

It can be precise if you have global information on the scheduling (eg. if you know that from a point onwards the queue is draining). But yes, in multi-threaded environments without external information all queries are stale the moment you make them.

1

u/Beginning-Safe4282 May 23 '26 edited May 23 '26

To me its usefull if we want to get a rough idea if the que is full or not without some global atomic counter, I know its not accurate as it could be stale by the time it returns the value, and I was Ok with that for the cases it was used, namely deciding whether some worker thread that was sleeping continue to sleep or to wake up.

Its not even needed for the actual queue, its something extra I added just incase any one is interested.

61

u/lxbrtn May 23 '26

wasEmptyVeryRecentlyAndMightStîllBe

11

u/thisismyfavoritename May 23 '26

stîll

1

u/lxbrtn May 23 '26

A little-known introspection cue (off-topic here)

13

u/ericonr May 23 '26

How do you correctly sleep on wasEmpty without impacting latency?

3

u/Beginning-Safe4282 May 23 '26 edited May 23 '26

The point is, you dont, its an extension API just to act as a reference, ideally you dont want to use it in a place where latency is very important, its for cases where a few it or misses are fine

-6

u/saf_e May 23 '26

A-a-and it has mutex! In lock free impl!

6

u/Beginning-Safe4282 May 23 '26

What? Did you even read the article?