1
votes

I have compared the elapse time used among these three cases, they are boost::lockfree::queue, boost::lockfree::spsc_queue and also the serial code of the producer/consumer queues using std::queue. I compiled and ran the boost example code of "spsc_queue.cpp", "queue.cpp" in "/apps/boost_1_56_0/libs/lockfree/examples" and below is the serial code to produce/consume the same number of objects.

The elapsed time spent for boost::lockfree::queue to produce/consume 400000000 objects is 290 seconds, and for boost::lockfree::spsc_queue (nowait single producer queue and single consumer queue) is 172.84 second. The code without multithreading is only for 17.35 seconds. I am wondering what's the point to use the multithreading lockfree queue. Is it just a demo to feature these two lockfree queues can be concurrently accessed ?

#include <queue>
#include <iostream>


int producer_count = 0;
int consumer_count = 0;

std::queue<int> q;

const int iterations = 400000000;

void producer(void)
{
    for (int i = 0; i != iterations; ++i) {
        int value = ++producer_count;
        q.push(value);
    }
}

void consumer(void)
{
    int value;

    while (!q.empty()) {
        value = q.front();
        q.pop();
        ++consumer_count;
    }
}

int main(int argc, char* argv[])
{
    using namespace std;

    producer();
    consumer();

    cout << "produced " << producer_count << " objects." << endl;
    cout << "consumed " << consumer_count << " objects." << endl;
}
2
queue allocates a node for each element, but caches node memory when elements are removed. Because all your insertions are first-time insertions, you are essentially measuring allocator performance. Try producing and consuming queue elements in a loop, it should be closer to real-world performance. - Anton3

2 Answers

0
votes

Yes, you are right!

The lockfree queues can be accessed concurrently in an multi threaded environment without producing any data races.

  • boost::lockfree::spsc_queue: a single produce single consumer queue
  • boost::lockfree::queue:a multi producer multi consumer queue

http://www.boost.org/doc/libs/1_59_0/doc/html/lockfree.html

0
votes

Lock free queues are of interest in real-time systems to avoid priority inversion. For example, if you are making an audio application, the GUI thread will need to communicate with the audio thread. If a queue with locks is used, and the low-priority GUI thread holds a lock to the queue for any length of time, when the audio thread, gets held at that lock, the audio will glitch. Using a lock free queue allows the audio thread to do it's call to the queue, without ever getting stuck waiting for a low-priority thread.