test_triple_buffer.cpp (1363B)
1 /* 2 * Copyright © 2022 Mozilla Foundation 3 * 4 * This program is made available under an ISC-style license. See the 5 * accompanying file LICENSE for details. 6 */ 7 8 /* cubeb_triple_buffer test */ 9 #include "gtest/gtest.h" 10 #if !defined(_XOPEN_SOURCE) 11 #define _XOPEN_SOURCE 600 12 #endif 13 #include "cubeb/cubeb.h" 14 #include "cubeb_triple_buffer.h" 15 #include <atomic> 16 #include <math.h> 17 #include <memory> 18 #include <stdio.h> 19 #include <stdlib.h> 20 #include <thread> 21 22 #include "common.h" 23 24 TEST(cubeb, triple_buffer) 25 { 26 struct AB { 27 uint64_t a; 28 uint64_t b; 29 }; 30 triple_buffer<AB> buffer; 31 32 std::atomic<bool> finished = {false}; 33 34 ASSERT_TRUE(!buffer.updated()); 35 36 auto t = std::thread([&finished, &buffer] { 37 AB ab; 38 ab.a = 0; 39 ab.b = UINT64_MAX; 40 uint64_t counter = 0; 41 do { 42 buffer.write(ab); 43 ab.a++; 44 ab.b--; 45 } while (counter++ < 1e6 && ab.a <= UINT64_MAX && ab.b != 0); 46 finished.store(true); 47 }); 48 49 AB ab; 50 AB old_ab; 51 old_ab.a = 0; 52 old_ab.b = UINT64_MAX; 53 54 // Wait to have at least one value produced. 55 while (!buffer.updated()) { 56 } 57 58 // Check that the values are increasing (resp. descreasing) monotonically. 59 while (!finished) { 60 ab = buffer.read(); 61 ASSERT_GE(ab.a, old_ab.a); 62 ASSERT_LE(ab.b, old_ab.b); 63 old_ab = ab; 64 } 65 66 t.join(); 67 68 buffer.invalidate(); 69 ASSERT_FALSE(buffer.updated()); 70 }