boost1.53中的lock-free

简介: boost1.53中的lock-free

原始网站:http://www.boost.org/doc/libs/1_53_0/doc/html/lockfree.html


 前言



  Boost1.53版本中新增加了lock-free库,终于有这么一款官方的lock-free结构出来了。以前在做高性能服务器处理的时候自己费了不少精力去网上搜索代码测试,不仅浪费精力而且可靠性还不敢保证。当然在项目中我使用最多的还是one-one的circle-buffer的方式,其实也就是boost::lockfree::spsc_queue,lock-free结构减少了大量的系统调用,因此特定场合下提升的性能还是非常明显的。总而言之,Boost的lock-free库还是比较值得期待和学习的。


  Non-blocking数据结构不再依赖于locks和mutexes去保证线程的安全。同步的操作完全在user-space完成,不需要直接和操作系统交互。不再依赖于guards,non-blocking数据结构需要atomic operations,尤其是CPU执行中不被中断。并不是所有的硬件支持相同系列的 atomic instructions,硬件不支持的将会使用gurard来进行模拟,当然这已经失去了lock-free的优势。


    影响lock-free的三种情况:



     Atomic Operations: 硬件提供atomic操作,这时候将会用spinlocks进行模拟,则会导致操作被block。


     
Memory Allocations:操作系统的内存分配不是lock-free的。因此没有办法去实现真正的dynamically-sized的数据结构。boost.lockfree使用memory pool去分配内部的nodes。如果memory pool耗尽,则新节点的内存需要向操作系统进行索取导致内存分配。但是对于boost.lockfree可以采用special call访问失败的方式来避免内存分配。见后续lock-free内存相关设置。


  Exception Handling:C++ exception处理没有任何保证其real-time处理的行为。因此我们不鼓励在excetion的处理中使用lock-free代码。


    Boost.lockfree实现了三种数据结构: 

 

boost::lockfree::queue: a lock-free multi-produced/multi-consumer queue     boost::lockfree::stack: a lock-free multi-produced/multi-consumer stack     boost::lockfree::spsc_queue: a wait-free single-producer/single-consumer queue (commonly known as ringbuffer)      

 lock-free内存相关设置:


  • boost::lockfree::fixed_sized, defaults to boost::lockfree::fixed_sized<false>Can be used to completely disable dynamic memory allocations during push in order to ensure lockfree behavior. If the data structure is configured as fixed-sized, the internal nodes are stored inside an array and they are addressed by array indexing. This limits the possible size of the queue to the number of elements that can be addressed by the index type (usually 2**16-2), but on platforms that lack double-width compare-and-exchange instructions, this is the best way to achieve lock-freedom.
  • boost::lockfree::capacity, optional If this template argument is passed to the options, the size of the queue is set at compile-time. It this option implies fixed_sized<true>
  • boost::lockfree::allocator, defaults to boost::lockfree::allocator<std::allocator<void>> Specifies the allocator that is used for the internal freelist

     

 Example


#include <boost/thread/thread.hpp>
#include <boost/lockfree/queue.hpp>
#include <iostream>
#include <boost/atomic.hpp>
boost::atomic_int producer_count(0);
boost::atomic_int consumer_count(0);
boost::lockfree::queue<int> queue(128);
const int iterations = 10000000;
const int producer_thread_count = 4;
const int consumer_thread_count = 4;
void producer(void)
{
    for (int i = 0; i != iterations; ++i) {
        int value = ++producer_count;
        while (!queue.push(value))
            ;
    }
}
boost::atomic<bool> done (false);
void consumer(void)
{
    int value;
    while (!done) {
        while (queue.pop(value))
            ++consumer_count;
    }
    while (queue.pop(value))
        ++consumer_count;
}
int main(int argc, char* argv[])
{
    using namespace std;
    cout << "boost::lockfree::queue is ";
    if (!queue.is_lock_free())
        cout << "not ";
    cout << "lockfree" << endl;
    boost::thread_group producer_threads, consumer_threads;
    for (int i = 0; i != producer_thread_count; ++i)
        producer_threads.create_thread(producer);
    for (int i = 0; i != consumer_thread_count; ++i)
        consumer_threads.create_thread(consumer);
    producer_threads.join_all();
    done = true;
    consumer_threads.join_all();
    cout << "produced " << producer_count << " objects." << endl;
    cout << "consumed " << consumer_count << " objects." << endl;
}


#include <boost/thread/thread.hpp>
#include <boost/lockfree/stack.hpp>
#include <iostream>
#include <boost/atomic.hpp>
boost::atomic_int producer_count(0);
boost::atomic_int consumer_count(0);
boost::lockfree::stack<int> stack(128);
const int iterations = 1000000;
const int producer_thread_count = 4;
const int consumer_thread_count = 4;
void producer(void)
{
    for (int i = 0; i != iterations; ++i) {
        int value = ++producer_count;
        while (!stack.push(value))
            ;
    }
}
boost::atomic<bool> done (false);
void consumer(void)
{
    int value;
    while (!done) {
        while (stack.pop(value))
            ++consumer_count;
    }
    while (stack.pop(value))
        ++consumer_count;
}
int main(int argc, char* argv[])
{
    using namespace std;
    cout << "boost::lockfree::stack is ";
    if (!stack.is_lock_free())
        cout << "not ";
    cout << "lockfree" << endl;
    boost::thread_group producer_threads, consumer_threads;
    for (int i = 0; i != producer_thread_count; ++i)
        producer_threads.create_thread(producer);
    for (int i = 0; i != consumer_thread_count; ++i)
        consumer_threads.create_thread(consumer);
    producer_threads.join_all();
    done = true;
    consumer_threads.join_all();
    cout << "produced " << producer_count << " objects." << endl;
    cout << "consumed " << consumer_count << " objects." << endl;
}


#include <boost/thread/thread.hpp>#include <boost/lockfree/spsc_queue.hpp>
#include <iostream>#include <boost/atomic.hpp>int producer_count = 0;
boost::atomic_int consumer_count (0);
boost::lockfree::spsc_queue<int, boost::lockfree::capacity<1024> > spsc_queue;
const int iterations = 10000000;void producer(void){
    for (int i = 0; i != iterations; ++i) {        int value = ++producer_count;
        while (!spsc_queue.push(value))            ;    }}
boost::atomic<bool> done (false);void consumer(void){    int value;
    while (!done) {        while (spsc_queue.pop(value))
            ++consumer_count;    }    while (spsc_queue.pop(value))
        ++consumer_count;}int main(int argc, char* argv[]){
    using namespace std;    cout << "boost::lockfree::queue is ";
    if (!spsc_queue.is_lock_free())        cout << "not ";
    cout << "lockfree" << endl;    boost::thread producer_thread(producer);
    boost::thread consumer_thread(consumer);    producer_thread.join();
    done = true;    consumer_thread.join();
    cout << "produced " << producer_count << " objects." << endl;
    cout << "consumed " << consumer_count << " objects." << endl;}




目录
相关文章
|
存储 设计模式 缓存
DDD领域驱动设计实战-分层架构及代码目录结构(下)
DDD领域驱动设计实战-分层架构及代码目录结构
2517 0
DDD领域驱动设计实战-分层架构及代码目录结构(下)
|
存储 安全 编译器
【Qt 底层机制之信号和槽 】深入探究Qt信号和槽背后的原理
【Qt 底层机制之信号和槽 】深入探究Qt信号和槽背后的原理
4208 4
|
C++ 索引
vscode clangd c++开发常见问题和解决方案
vscode clangd c++开发常见问题和解决方案
4575 0
|
12月前
|
存储 编解码 JSON
16 RPC 实战:剖析 gRPC 源码,动手实现一个完整的 RPC
本课通过剖析gRPC源码,实战实现完整RPC框架。从动态代理、序列化到HTTP/2协议,详解请求发送与接收流程,涵盖Stub生成、数据封装、Frame传输、Netty编解码等核心机制,助你掌握高性能RPC设计精髓。
|
机器学习/深度学习 人工智能 算法
AI鱼类识别技术原理及示例代码
本文详细解析了AI鱼类识别的代码示例,涵盖深度学习框架选择、数据集处理、模型构建与训练优化全流程。内容包括技术选型对比(如TensorFlow、PyTorch、YOLO系列)、数据准备流程(开源数据集与标注规范)、完整代码示例(以PyTorch版ResNet50改进模型为例)以及模型优化策略(如量化压缩、知识蒸馏)。此外,还提供了典型应用场景(如渔业资源监测系统)、模型评估指标及开源项目推荐,并针对常见问题(小样本、水下模糊、类别不平衡等)提出解决方案。
1413 5
|
消息中间件 缓存 Java
RocketMQ消息发送常见错误与解决方案
RocketMQ消息发送常见错误与解决方案
RocketMQ消息发送常见错误与解决方案
|
程序员 编译器 C语言
C中的 malloc 和C++中的 new 有什么区别
在C语言中,`malloc`函数用于在运行时分配内存,返回指向所分配内存的指针,需显式包含头文件 `&lt;stdlib.h&gt;`。而在C++中,`new`不仅分配内存,还对其进行构造初始化,且直接使用类型声明即可,无需额外包含头文件。`new`还支持数组初始化,能更好地融入C++的面向对象特性,而`malloc`仅作为内存分配工具。使用完毕后,`free`和`delete`分别用于释放`malloc`和`new`分配的内存。
801 21
|
网络协议 Linux 网络安全
SYN Cookie技术原理
【8月更文挑战第21天】
1095 1
|
开发框架 Dart Java
Flutter的核心:Dart语言基础——语法与特性深度解析
【4月更文挑战第26天】Flutter框架背后的Dart语言,以其简洁的语法和独特特性深受开发者喜爱。本文深入解析Dart的语法与特性,如类型推导、动态静态类型系统、统一的类接口、访问权限控制以及并发编程支持。了解并掌握Dart,能助开发者更高效地利用Flutter构建高性能移动应用。
|
缓存 Linux 虚拟化
Linux下top命令指标说明
Linux下top命令指标说明
2317 0