wrote basic tests for spinlock and fixed a bug in the spinlock class
This commit is contained in:
parent
813bd4a424
commit
a2ba8f14d3
3
test/.gitignore
vendored
3
test/.gitignore
vendored
@ -1,5 +1,6 @@
|
||||
# ignore object files
|
||||
# ignore object and executable files
|
||||
*.o
|
||||
tests
|
||||
|
||||
# ignore the library, download your own copy via install.sh
|
||||
catch.hpp
|
||||
|
@ -1,7 +1,8 @@
|
||||
TARGET = tests
|
||||
LIBS = -lm
|
||||
CC = c++
|
||||
CFLAGS = -g -Wall
|
||||
CFLAGS = -g -Wall -std=c++1y
|
||||
INCLUDE = "../"
|
||||
|
||||
.PHONY: default all clean
|
||||
|
||||
@ -12,13 +13,17 @@ OBJECTS = $(patsubst %.cpp, %.o, $(wildcard *.cpp))
|
||||
HEADERS = $(wildcard *.hpp)
|
||||
|
||||
%.o: %.cpp $(HEADERS)
|
||||
$(CC) $(CFLAGS) -c $< -o $@
|
||||
$(CC) $(CFLAGS) -I $(INCLUDE) -c $< -o $@
|
||||
|
||||
.PRECIOUS: $(TARGET) $(OBJECTS)
|
||||
|
||||
$(TARGET): $(OBJECTS)
|
||||
$(CC) $(OBJECTS) -Wall $(LIBS) -o $@
|
||||
$(CC) $(OBJECTS) -Wall $(LIBS) -o $@
|
||||
|
||||
clean:
|
||||
-rm -f *.o
|
||||
-rm -f $(TARGET)
|
||||
-rm -f *.o
|
||||
-rm -f $(TARGET)
|
||||
|
||||
test:
|
||||
make
|
||||
./tests --success
|
||||
|
49
test/spinlock.cpp
Normal file
49
test/spinlock.cpp
Normal file
@ -0,0 +1,49 @@
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
|
||||
#include "catch.hpp"
|
||||
#include "utils/sync/spinlock.hpp"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
TEST_CASE("a thread can acquire and release the lock", "[spinlock]")
|
||||
{
|
||||
SpinLock lock;
|
||||
|
||||
lock.acquire();
|
||||
// i have a lock
|
||||
lock.release();
|
||||
|
||||
REQUIRE(true);
|
||||
}
|
||||
|
||||
int x = 0;
|
||||
|
||||
SpinLock lock;
|
||||
|
||||
void test_lock()
|
||||
{
|
||||
using namespace std::literals;
|
||||
|
||||
lock.acquire();
|
||||
x++;
|
||||
|
||||
REQUIRE(x < 2);
|
||||
std::this_thread::sleep_for(1s);
|
||||
|
||||
x--;
|
||||
lock.release();
|
||||
}
|
||||
|
||||
TEST_CASE("only one thread at a time can own the lock", "[spinlock]")
|
||||
{
|
||||
std::vector<std::thread> threads;
|
||||
|
||||
for(int i = 0; i < 10; ++i)
|
||||
threads.push_back(std::thread(test_lock));
|
||||
|
||||
for(auto& thread : threads){
|
||||
thread.join();
|
||||
}
|
||||
}
|
@ -19,7 +19,7 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
std::atomic_flag lock;
|
||||
std::atomic_flag lock = ATOMIC_FLAG_INIT;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
Loading…
Reference in New Issue
Block a user