ScopeGuard

Defined in header <Kokkos_Core.hpp>

Usage

Kokkos::ScopeGuard guard(argc, argv);
Kokkos::ScopeGuard guard(Kokkos::InitializationSettings()
                            .set_map_device_id_by("random")
                            .set_num_threads(1));
Kokkos::ScopeGuard guard;

ScopeGuard is a class to initialize and finalize Kokkos using RAII. It calls initialize() with the provided arguments in the constructor and finalize() in the destructor.

Interface

class ScopeGuard

A class calling initialize() at the start of its lifetime and finalize() at the end of its lifetime.

template<class ...Args>
ScopeGuard(Args&&... args);
Parameters:

args – arguments to pass to initialize()

Possible implementation:

template <class... Args> ScopeGuard(Args&&... args){
  initialize(std::forward<Args>(args)...);
}
~ScopeGuard();

Possible implementation:

~ScopeGuard() { finalize(); }
ScopeGuard(ScopeGuard const&) = delete;

Copy constructor

ScopeGuard(ScopeGuard&&) = delete;

Move constructor

ScopeGuard &operator=(ScopeGuard const&) = delete;

Copy assignment operator

ScopeGuard &operator=(ScopeGuard&&) = delete;

Move assignment operator

Notes

Caution

Using ScopeGuard is mutually exclusive with calling initialize() and finalize() directly. Furthermore, only a single ScopeGuard object can be created during the lifetime of the program, and most Kokkos functionality can only be used during the lifetime of that object.

Kokkos::ScopeGuard(argc, argv);  // Temporary object get destroyed immediately and
//                ^                 the Kokkos execution environment is finalized with it
//                Forgot to define a named variable
Kokkos::View<int> v("v");  // ERROR Kokkos finalized

Note

ScopeGuard unconditionally forwards the provided arguments to initialize(), which means they have the same preconditions. Until version 3.7, ScopeGuard was calling initialize() in its constructor if and only if is_initialized() would return false, and it was calling finalize() in its destructor if and only if it called initialize() in its constructor.

We dropped support for the old behavior. If you think you really need it, you may do:

auto guard = Kokkos::is_initialized()
                 ? std::make_optional<Kokkos::ScopeGuard>()
                 : std::nullopt;

Example

int main(int argc, char* argv[]) {
    Kokkos::ScopeGuard guard(argc, argv);
    Kokkos::View<double*> my_view("my_view", 10);
    // my_view destructor called before Kokkos::finalize
    // ScopeGuard destructor called, calls Kokkos::finalize
}

See also

See also

initialize

Start the Kokkos execution environment.

finalize

Terminate the Kokkos execution environment.