feat: test for mutex (make this better)

This commit is contained in:
maelstrom 2026-05-28 18:04:25 +02:00
commit ee8ff11712

View file

@ -1,5 +1,8 @@
#include "fishbone/thread.h"
#include <catch2/catch_test_macros.hpp>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
struct thread_arg {
int& a;
@ -30,4 +33,27 @@ TEST_CASE("Thread") {
th.join();
REQUIRE(a == 100);
}
TEST_CASE("Mutex") {
for (int i = 0; i < 100; i++) {
int a = 0;
fishbone::Mutex m;
fishbone::Thread::CallableFunc func = [&a, &m](auto) {
m.lock();
for (int j = 0; j < 2; j++) {
int b = a;
usleep((60 * rand()) / RAND_MAX);
a = ++b;
}
m.unlock();
};
fishbone::Thread th1(func), th2(func);
th1.join();
th2.join();
REQUIRE(a == 4);
}
}