您的位置:首页 > 财经 > 金融 > 服装与服饰设计_美国etsy网站_石家庄最新疫情_企业网站建设方案书

服装与服饰设计_美国etsy网站_石家庄最新疫情_企业网站建设方案书

2024/12/23 9:48:00 来源:https://blog.csdn.net/qianbo042311/article/details/142602109  浏览:    关键词:服装与服饰设计_美国etsy网站_石家庄最新疫情_企业网站建设方案书
服装与服饰设计_美国etsy网站_石家庄最新疫情_企业网站建设方案书

boost 的lockfree 使用

// test.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#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;//1000 second;// 000TicToc tp;std::thread thread_producer([=,&tp]() {//every ten millonsecond to 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;//condition_producers.notify_one();}elseboost::this_thread::sleep(1);}std::cout << tp.toc()<< " the insert is over " << std::endl;/*	while (ncount != 1000000 - 1){condition_producers.notify_one();std::cout << "sleep" <<ncount<< std::endl;lee_mill(20);}done = 1;*/});std::thread thread_consume([]() {TicToc tc;while (!done){std::unique_lock<std::mutex> ul(pro_mtx);//condition_producers.wait(ul);// , [] {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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com