|
| 1 | +/* |
| 2 | + * Copyright (c), 2025, George Sedov |
| 3 | + * |
| 4 | + * Distributed under the Boost Software License, Version 1.0. |
| 5 | + * (See accompanying file LICENSE_1_0.txt or copy at |
| 6 | + * http://www.boost.org/LICENSE_1_0.txt) |
| 7 | + * |
| 8 | + */ |
| 9 | +#include <iostream> |
| 10 | +#include <string> |
| 11 | +#include <thread> |
| 12 | +#include <vector> |
| 13 | + |
| 14 | +#include <highfive/highfive.hpp> |
| 15 | + |
| 16 | +const std::string file_name("swmr_read_write.h5"); |
| 17 | +const std::string dataset_name("array"); |
| 18 | + |
| 19 | +/** |
| 20 | + * This is the SWMR writer. |
| 21 | + * It should be used in conjunction with SWMR reader (see swmr_read example) |
| 22 | + */ |
| 23 | +int main(void) { |
| 24 | + using namespace HighFive; |
| 25 | + |
| 26 | + // Create a new file |
| 27 | + // For SWMR we need to force the latest header, which is passed in AccessProps |
| 28 | + FileAccessProps fapl; |
| 29 | + fapl.add(FileVersionBounds(H5F_LIBVER_LATEST, H5F_LIBVER_LATEST)); |
| 30 | + File file(file_name, File::Truncate, fapl); |
| 31 | + |
| 32 | + // To make sense for SWMR, the dataset should be extendable, and hence - chunkable |
| 33 | + DataSetCreateProps props; |
| 34 | + props.add(Chunking({1})); |
| 35 | + auto dataset = |
| 36 | + file.createDataSet<int>(dataset_name, DataSpace({0ul}, {DataSpace::UNLIMITED}), props); |
| 37 | + |
| 38 | + // Start the SWMR write |
| 39 | + // you are not allowed to create new data headers (i.e. DataSets, Groups, and Attributes) after |
| 40 | + // that, you should also make sure all the Groups and Attributes are closed (i.e. the objects |
| 41 | + // representing them are out of scope or destroyed) before calling this function |
| 42 | + // see HDF5 SWMR tutorial for details |
| 43 | + file.startSWMRWrite(); |
| 44 | + |
| 45 | + // If you want to open an already-existing file for SWMR write, use |
| 46 | + // File file(file_name, File::WriteSWMR); |
| 47 | + // auto dataset = file.getDataSet(dataset_name); |
| 48 | + |
| 49 | + std::cout << "Started the SWMR write" << std::endl; |
| 50 | + |
| 51 | + // Let's write to file. |
| 52 | + for (int i = 0; i < 10; i++) { |
| 53 | + // resize the dataset to fit the new element |
| 54 | + dataset.resize({static_cast<size_t>(i + 1)}); |
| 55 | + // select the dataset slice and write the number to it |
| 56 | + dataset.select({static_cast<size_t>(i)}, {1ul}).write(i); |
| 57 | + // in SWMR mode you need to explicitly flush the DataSet |
| 58 | + dataset.flush(); |
| 59 | + |
| 60 | + // give time for the reader to react |
| 61 | + std::this_thread::sleep_for(std::chrono::milliseconds(100)); |
| 62 | + } |
| 63 | + |
| 64 | + return 0; |
| 65 | +} |
0 commit comments