|
| 1 | +// SPDX-License-Identifier: BSD-3-Clause |
| 2 | +/* Copyright 2021, Intel Corporation */ |
| 3 | + |
| 4 | +/* |
| 5 | + * pool_as_class_member.cpp -- Example shows how to manage pool using RAII |
| 6 | + * idiom. |
| 7 | + */ |
| 8 | + |
| 9 | +#include <iostream> |
| 10 | +//! [pool_class_member_example] |
| 11 | +#include <libpmemobj++/p.hpp> |
| 12 | +#include <libpmemobj++/persistent_ptr.hpp> |
| 13 | +#include <libpmemobj++/pool.hpp> |
| 14 | + |
| 15 | +using namespace pmem::obj; |
| 16 | + |
| 17 | +class Foo { |
| 18 | +private: |
| 19 | + /* pool root structure */ |
| 20 | + struct persistent_data { |
| 21 | + p<int> some_variable; |
| 22 | + }; |
| 23 | + |
| 24 | + using pool_type = pmem::obj::pool<persistent_data>; |
| 25 | + /* pool object */ |
| 26 | + pool_type pop; |
| 27 | + |
| 28 | + const char *layout = "pool_layout"; |
| 29 | + |
| 30 | +public: |
| 31 | + Foo(const char *poolfile_path) |
| 32 | + { |
| 33 | + /* Create a pmemobj pool. */ |
| 34 | + if (pool_type::check(poolfile_path, layout) == 1) { |
| 35 | + pop = pool_type::open(poolfile_path, layout); |
| 36 | + } else { |
| 37 | + std::cerr << "Cannot open pool" << std::endl |
| 38 | + << "Trying to create a new one " << std::endl; |
| 39 | + pop = pool_type::create("poolfile", layout, |
| 40 | + PMEMOBJ_MIN_POOL); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + Foo() = delete; |
| 45 | + |
| 46 | + ~Foo() |
| 47 | + { |
| 48 | + /* Close a pmemobj pool */ |
| 49 | + pop.close(); |
| 50 | + } |
| 51 | + |
| 52 | + void |
| 53 | + set(int variable) |
| 54 | + { |
| 55 | + auto root_obj = pop.root(); |
| 56 | + root_obj->some_variable = variable; |
| 57 | + pop.persist(root_obj->some_variable); |
| 58 | + } |
| 59 | + |
| 60 | + void |
| 61 | + increment() |
| 62 | + { |
| 63 | + set(pop.root()->some_variable + 1); |
| 64 | + } |
| 65 | + |
| 66 | + void |
| 67 | + print() |
| 68 | + { |
| 69 | + std::cout << pop.root()->some_variable << std::endl; |
| 70 | + } |
| 71 | +}; |
| 72 | + |
| 73 | +void |
| 74 | +pool_example() |
| 75 | +{ |
| 76 | + auto foo = Foo("poolfile"); |
| 77 | + foo.print(); |
| 78 | + foo.set(42); |
| 79 | + foo.print(); |
| 80 | + foo.increment(); |
| 81 | + foo.print(); |
| 82 | +} |
| 83 | +//! [pool_class_member_example] |
| 84 | + |
| 85 | +int |
| 86 | +main() |
| 87 | +{ |
| 88 | + try { |
| 89 | + pool_example(); |
| 90 | + } catch (const std::exception &e) { |
| 91 | + std::cerr << "Exception " << e.what() << std::endl; |
| 92 | + return -1; |
| 93 | + } |
| 94 | + |
| 95 | + return 0; |
| 96 | +} |
0 commit comments