boost 的lockfree 使用
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <mutex>
#include <memory>
#include <condition_variable>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/thread/thread.hpp>
#include <boost/atomic.hpp>
#include <thread>boost::atomic_int con_count(0);
boost::atomic_bool done(false);std::mutex pro_mtx;
std::condition_variable condition_producers;#include "c_mmu.h"
class TicToc
{
public:TicToc(){tic();}void tic(){start = std::chrono::system_clock::now();}double toc(){end = std::chrono::system_clock::now();std::chrono::duration<double> elapsed_seconds = end - start;start = end;return elapsed_seconds.count() * 1000;}private:std::chrono::time_point<std::chrono::system_clock> start, end;
};struct s_data
{uint8_t* data = NULL;size_t len = 0;s_data(const char* in){len = strlen(in);data = (uint8_t*)malloc(len+1);if (data == NULL)return;memcpy(data, in, len);data[len] = '\0';}~s_data(){if (data != NULL)free(data);}
};
typedef std::shared_ptr<s_data> ptr_s_data;
boost::lockfree::spsc_queue<ptr_s_data, boost::lockfree::capacity<100> > spsc_queue;
static int ncount = 0;#define lee_mill(x) std::this_thread::sleep_for(std::chrono::milliseconds(x))int main_()
{if (spsc_queue.is_lock_free())std::cout << "single producer, single consume" << std::endl;TicToc tp;std::thread thread_producer([=,&tp]() {int insert_num = 0;for (;;){if (spsc_queue.write_available()){char buffer[128];sprintf(buffer, "this is test %d\n", insert_num);ptr_s_data obj = std::make_shared<s_data>(buffer);spsc_queue.push(obj);if (insert_num++ > 100000)break;}elseboost::this_thread::sleep(1);}std::cout << tp.toc()<< " the insert is over " << std::endl;});std::thread thread_consume([]() {TicToc tc;while (!done){std::unique_lock<std::mutex> ul(pro_mtx);if (spsc_queue.read_available() > 0){ptr_s_data obj = nullptr;spsc_queue.pop(obj);ncount++;if (obj && obj->data != NULL){if ((ncount % 10000) == 0)std::cout << obj->data;}}elselee_mill(2);}std::cout << "left is " << spsc_queue.read_available() << std::endl;std::cout << tc.toc() << " consume is over" << std::endl;});thread_producer.join();done = true;thread_consume.join();std::cout << "消费的数目:" << con_count << std::endl;return 1;
}