I'm quite new in multithreading programming, I just know the most common Producer-Consumer-Queue. I'm using the boost c++ libraries and I don't know if is better use boost::lockfree::queue or a wrapper class around std::queue that is using `mutex` and `condition_variable`.
Where is better using lock free data structures and where is better is use a simple implementation based on `mutex` and `condition_variables`?
Lockfree queue is slower than using mutexes.
Lock-free queue is a queue applying to concurrency but without locking. When using lock-free queue, slow or stopped processes do not prevent other processes from accessing data in it. Lock-free queue has two main interfaces just like normal queue: Enqueue.
Description. The spsc_queue class provides a single-writer/single-reader fifo queue, pushing and popping is wait-free. Policies: boost::lockfree::capacity<> , optional. If this template argument is passed to the options, the size of the ringbuffer is set at compile-time.
The C++ thread safe queue allows to use the queue by multiple thread in multi-threaded code. The thread safe queue is not a built-in method or class in C++; it can be implemented with the help of built-in STL libraries.
Try both in your app, see which performs best.
Typically, polling a lock-free queue works best when the queue nearly always has entries, a blocking queue works best when the queue is nearly always empty.
The downside of blocking queues is latency, typically of the order of 2-20 uS, due to kernel signaling. This can be mitigated by designing the system so that the work done by the consumer threads on each queued item takes much longer than this interval.
The downside of non-blocking queues is the waste of CPU and memory bandwidth while polling an empty queue. This can be mitigated by designing the system so that the queue is rarely empty.
As already hinted at by commenters, a non-blocking queue is a very bad idea on single-CPU systems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With