You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为tbb::concurrent_vector实现boost::serialize序列化

实现tbb::concurrent_vector的Boost Serialization支持

核心思路

tbb::concurrent_vector和std::vector的接口高度兼容(提供size()、迭代器、push_back()等方法),因此可以直接复用Boost Serialization对序列容器的序列化逻辑,无需从零实现。通过在boost::serialization命名空间下特化序列化函数,就能让Boost自动识别并处理concurrent_vector。

具体实现代码

首先包含必要的头文件,然后编写序列化/反序列化的模板特化:

#include <tbb/concurrent_vector.h>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/split_member.hpp>

namespace boost {
namespace serialization {

// 统一入口,拆分save/load逻辑
template<class Archive, class T, class Allocator>
void serialize(Archive& ar, tbb::concurrent_vector<T, Allocator>& vec, const unsigned int version)
{
    split_member(ar, vec, version);
}

// 序列化(保存)逻辑
template<class Archive, class T, class Allocator>
void save(Archive& ar, const tbb::concurrent_vector<T, Allocator>& vec, const unsigned int /*version*/)
{
    const auto size = vec.size();
    ar << size;
    // 遍历容器逐个序列化元素
    for (const auto& elem : vec) {
        ar << elem;
    }
}

// 反序列化(加载)逻辑
template<class Archive, class T, class Allocator>
void load(Archive& ar, tbb::concurrent_vector<T, Allocator>& vec, const unsigned int /*version*/)
{
    typename tbb::concurrent_vector<T, Allocator>::size_type size;
    ar >> size;
    // 预分配空间减少扩容开销
    vec.reserve(size);
    for (decltype(size) i = 0; i < size; ++i) {
        T elem;
        ar >> elem;
        vec.push_back(elem);
    }
}

} // namespace serialization
} // namespace boost

关键注意事项

  • 元素可序列化性:确保容器内的T类型本身支持Boost Serialization(内置类型、STL容器默认支持,自定义类型需自行实现serialize函数)。
  • 线程安全:序列化/反序列化过程中,必须保证没有其他线程修改目标concurrent_vector——该容器的线程安全是针对并发读写设计的,但序列化是单线程操作,期间容器需处于只读状态。
  • 版本兼容:如果后续需要修改序列化逻辑,可以利用version参数做版本兼容处理。

使用示例

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <fstream>
#include <iostream>

int main()
{
    // 初始化并发容器
    tbb::concurrent_vector<int> src_vec = {1, 2, 3, 4, 5};

    // 序列化到文本文件
    std::ofstream ofs("concurrent_vec_data.txt");
    boost::archive::text_oarchive oa(ofs);
    oa << src_vec;
    ofs.close();

    // 从文件反序列化
    tbb::concurrent_vector<int> dest_vec;
    std::ifstream ifs("concurrent_vec_data.txt");
    boost::archive::text_iarchive ia(ifs);
    ia >> dest_vec;
    ifs.close();

    // 验证结果
    for (int num : dest_vec) {
        std::cout << num << " ";
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者Some_Geeza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 00:43:20