Commit 51cc6572 by FritzFlorian

Add spinlock and tests for it.

parent 7dfa2a34
Pipeline #1099 failed with stages
in 1 minute 47 seconds
...@@ -26,6 +26,10 @@ namespace pls { ...@@ -26,6 +26,10 @@ namespace pls {
} }
} }
} }
void unlock() {
flag_.clear(std::memory_order_release);
}
}; };
} }
} }
......
add_executable(tests add_executable(tests
main.cpp main.cpp
example_tests.cpp example_tests.cpp
thread_tests.cpp) base_tests.cpp)
target_link_libraries(tests catch2 pls) target_link_libraries(tests catch2 pls)
\ No newline at end of file
#include <catch.hpp>
#include <pls/internal/base/thread.h>
#include <pls/internal/base/spin_lock.h>
#include <vector>
using namespace pls::internal::base;
using namespace std;
static bool base_tests_visited;
static int base_tests_local_value_one;
static vector<int> base_tests_local_value_two;
TEST_CASE( "thread creation and joining", "[internal/base/thread.h]") {
base_tests_visited = false;
auto t1 = start_thread([]() { base_tests_visited = true; });
t1.join();
REQUIRE(base_tests_visited);
}
TEST_CASE( "thread state", "[internal/base/thread.h]") {
int state_one = 1;
vector<int> state_two{1, 2};
auto t1 = start_thread([]() { base_tests_local_value_one = *this_thread::state<int>(); }, &state_one);
auto t2 = start_thread([]() { base_tests_local_value_two = *this_thread::state<vector<int>>(); }, &state_two);
t1.join();
t2.join();
REQUIRE(base_tests_local_value_one == 1);
REQUIRE(base_tests_local_value_two == vector<int>{1, 2});
}
TEST_CASE( "spinlock protects concurrent counter", "[internal/base/spinlock.h]") {
constexpr int num_iterations = 1000000;
int shared_counter = 0;
spin_lock lock{};
auto t1 = start_thread([&] () {
for (int i = 0; i < num_iterations; i++) {
lock.lock();
shared_counter++;
lock.unlock();
}
});
auto t2 = start_thread([&] () {
for (int i = 0; i < num_iterations; i++) {
lock.lock();
shared_counter--;
lock.unlock();
}
});
t1.join();
t2.join();
REQUIRE(shared_counter == 0);
}
#include <catch.hpp>
#include <pls/internal/base/thread.h>
#include <vector>
using namespace pls::internal::base;
using namespace std;
static bool visited;
static int local_value_1;
static vector<int> local_value_two;
TEST_CASE( "thread creation and joining", "[internal/base/thread.h]") {
visited = false;
auto t1 = start_thread([]() { visited = true; });
t1.join();
REQUIRE(visited);
}
TEST_CASE( "thread state", "[internal/base/thread.h]") {
int state_one = 1;
vector<int> state_two{1, 2};
auto t1 = start_thread([]() { local_value_1 = *this_thread::state<int>(); }, &state_one);
auto t2 = start_thread([]() { local_value_two = *this_thread::state<vector<int>>(); }, &state_two);
t1.join();
t2.join();
REQUIRE(local_value_1 == 1);
REQUIRE(local_value_two == vector<int>{1, 2});
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment