// tests/mgpu/device_guard_test.cpp - DeviceGuard switches the current device and puts it back. Needs one GPU (two for the switching checks); // exit 77 = a stated skip on a machine with none. #include "strata/mgpu/device_guard.hpp" #include #include using strata::mgpu::DeviceGuard; namespace { int g_fail = 0; void check(bool ok, const std::string& what) { if (ok) return; std::fprintf(stderr, "FAIL: %s\n", what.c_str()); ++g_fail; } } // namespace int main() { const int n = DeviceGuard::count(); if (n < 1) { std::puts("SKIPPED: mgpu_device_guard_test needs a GPU"); return 77; } std::printf("devices: %d\n", n); { DeviceGuard g0(0); check(g0.ok() && DeviceGuard::current() == 0, "a guard on device 0 makes it current"); } { DeviceGuard bad(n + 100); check(!bad.ok() && bad.error()[0] != '\0', "a guard on a device that does not exist is not ok and says why"); check(DeviceGuard::current() == 0, "a failed switch leaves the current device alone"); } { DeviceGuard same(0); check(same.ok() && same.previous() == 0 && DeviceGuard::current() == 0, "a guard on the device that is already current changes nothing"); } if (n >= 2) { { DeviceGuard g1(1); check(g1.ok() && DeviceGuard::current() == 1 && g1.previous() == 0, "a guard on device 1 switches to it and remembers 0"); { DeviceGuard g0(0); check(DeviceGuard::current() == 0 && g0.previous() == 1, "a nested guard switches back and remembers 1"); } check(DeviceGuard::current() == 1, "leaving the nested guard returns to 1"); } check(DeviceGuard::current() == 0, "leaving the outer guard returns to 0"); for (int round = 0; round < 100; ++round) { // many switches leave no drift DeviceGuard a(round % n); DeviceGuard b((round + 1) % n); } check(DeviceGuard::current() == 0, "a hundred nested switches end where they began"); } else { std::puts("one device: the switching checks are skipped"); } if (g_fail != 0) { std::fprintf(stderr, "%d check(s) failed\n", g_fail); return 1; } std::puts("mgpu_device_guard_test: all checks passed"); return 0; }