|
| 1 | +#include "src/__support/CPP/atomic.h" |
| 2 | +#include "src/__support/mpmc_stack.h" |
| 3 | +#include "src/pthread/pthread_create.h" |
| 4 | +#include "src/pthread/pthread_join.h" |
| 5 | +#include "test/IntegrationTest/test.h" |
| 6 | + |
| 7 | +using namespace LIBC_NAMESPACE; |
| 8 | + |
| 9 | +void smoke_test() { |
| 10 | + MPMCStack<int> stack; |
| 11 | + for (int i = 0; i <= 100; ++i) |
| 12 | + if (!stack.push(i)) |
| 13 | + __builtin_trap(); |
| 14 | + for (int i = 100; i >= 0; --i) |
| 15 | + if (*stack.pop() != i) |
| 16 | + __builtin_trap(); |
| 17 | + if (stack.pop()) |
| 18 | + __builtin_trap(); // Should be empty now. |
| 19 | +} |
| 20 | + |
| 21 | +void multithread_test() { |
| 22 | + constexpr static size_t NUM_THREADS = 5; |
| 23 | + constexpr static size_t NUM_PUSHES = 100; |
| 24 | + struct State { |
| 25 | + MPMCStack<size_t> stack; |
| 26 | + cpp::Atomic<size_t> counter = 0; |
| 27 | + cpp::Atomic<bool> flags[NUM_PUSHES]; |
| 28 | + } state; |
| 29 | + pthread_t threads[NUM_THREADS]; |
| 30 | + for (size_t i = 0; i < NUM_THREADS; ++i) { |
| 31 | + LIBC_NAMESPACE::pthread_create( |
| 32 | + &threads[i], nullptr, |
| 33 | + [](void *arg) -> void * { |
| 34 | + State *state = static_cast<State *>(arg); |
| 35 | + for (;;) { |
| 36 | + size_t current = state->counter.fetch_add(1); |
| 37 | + if (current >= NUM_PUSHES) |
| 38 | + break; |
| 39 | + if (!state->stack.push(current)) |
| 40 | + __builtin_trap(); |
| 41 | + } |
| 42 | + while (auto res = state->stack.pop()) |
| 43 | + state->flags[res.value()].store(true); |
| 44 | + return nullptr; |
| 45 | + }, |
| 46 | + &state); |
| 47 | + } |
| 48 | + for (pthread_t thread : threads) |
| 49 | + LIBC_NAMESPACE::pthread_join(thread, nullptr); |
| 50 | + while (cpp::optional<size_t> res = state.stack.pop()) |
| 51 | + state.flags[res.value()].store(true); |
| 52 | + for (size_t i = 0; i < NUM_PUSHES; ++i) |
| 53 | + if (!state.flags[i].load()) |
| 54 | + __builtin_trap(); |
| 55 | +} |
| 56 | + |
| 57 | +TEST_MAIN() { |
| 58 | + smoke_test(); |
| 59 | + multithread_test(); |
| 60 | + return 0; |
| 61 | +} |
0 commit comments