114
The locks parameter is a variadic template. Thanks to the std::function, a myriad
of types can be passed in to run. One of the preferred ways is to pass a lambda function
as the tx parameter. This makes the code compact and easier to analyze. Listing 8-1
shows how lambda can be used to perform work in a transaction.
Listing 8-1. Function object transaction
45
// execute a transaction
46
pmem::obj::transaction::run(pop, [&]() {
47
// do transactional work
48
});
Of course, this API is not limited to just lambda functions. Any callable target can
be passed as tx, such as functions, bind expressions, function objects, and pointers
to member functions. Since run is a normal static member function, it has the benefit
of being able to throw exceptions. If an exception is thrown during the execution of
a transaction, it is automatically aborted, and the active exception is rethrown so
information about the interruption is not lost. If the underlying C library fails for any
reason, the transaction is also aborted, and a C++ library exception is thrown. The
developer is no longer burdened with the task of checking the status of the previous
transaction.
libpmemobj-cpp transactions provide an entry point for persistent memory resident
synchronization primitives such as pmem::obj::mutex, pmem::obj::shared_mutex and
pmem::obj::timed_mutex. libpmemobj ensures that all locks are properly reinitialized
when one attempts to acquire a lock for the first time. The use of pmem locks is
completely optional, and transactions can be executed without them. The number of
supplied locks is arbitrary, and the types can be freely mixed. The locks are held until
the end of the given transaction, or the outermost transaction in the case of nesting. This
means when transactions are enclosed by a try-catch statement, the locks are released
before reaching the catch clause. This is extremely important in case some kind of
transaction abort cleanup needs to modify the shared state. In such a case, the necessary
locks need to be reacquired in the correct order.
Chapter 8 libpmemobj-Cpp: the adaptable language - C++ and persistent memory
Précédent

- 140/457

Suivant