wrote basic tests for spinlock and fixed a bug in the spinlock class

This commit is contained in:
Dominik Tomičević 2015-06-18 15:27:06 +02:00
parent 813bd4a424
commit a2ba8f14d3
4 changed files with 62 additions and 7 deletions

3
test/.gitignore vendored
View File

@ -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

View File

@ -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
View 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();
}
}

View File

@ -19,7 +19,7 @@ public:
}
private:
std::atomic_flag lock;
std::atomic_flag lock = ATOMIC_FLAG_INIT;
};
#endif