use methods that allows better handling of dummies

This commit is contained in:
2020-12-30 19:18:23 +01:00
parent 337ca9b169
commit a5eb49bc2e
2 changed files with 34 additions and 10 deletions

View File

@@ -14,9 +14,8 @@ class FineSet {
}; };
FineSet::FineSet(){ FineSet::FineSet(){
first = new Node(); // dummy node; first = Node::Dummy(); // dummy node;
Node* last = new Node(); Node* last = Node::Dummy();
last->data = INT_MAX; // end node;
first->next = last; first->next = last;
} }
@@ -25,20 +24,19 @@ bool FineSet::add(int element) {
Node* p = this->first; Node* p = this->first;
Node* c = p->next; Node* c = p->next;
c->lock(); c->lock();
while (c->data < element) { while (c->is_smaller_than(element)) {
p->unlock(); p->unlock();
p = c; p = c;
c = c->next; c = c->next;
c->lock(); c->lock();
} }
if (c->data == element) { if (c->is_equal(element)) {
c->unlock(); c->unlock();
p->unlock(); p->unlock();
return false; return false;
} else { } else {
Node* n = new Node(); Node* n = new Node(element);
n->data = element;
n->next = c; n->next = c;
p->next = n; p->next = n;
@@ -54,7 +52,7 @@ bool FineSet::rmv(int element) {
Node* c = p->next; Node* c = p->next;
c->lock(); c->lock();
while (c->data < element) { while (c->is_smaller_than(element)) {
p->unlock(); p->unlock();
c = c->next; c = c->next;
c->lock(); c->lock();
@@ -78,13 +76,13 @@ bool FineSet::ctn(int element) {
Node* c = p->next; Node* c = p->next;
c->lock(); c->lock();
while (c->data < element) { while (c->is_smaller_than(element)) {
p->unlock(); p->unlock();
c = c->next; c = c->next;
c->lock(); c->lock();
} }
if (c->data == element) { if (c->is_equal(element)) {
c->unlock(); c->unlock();
p->unlock(); p->unlock();
return true; return true;

View File

@@ -3,12 +3,38 @@
class Node { class Node {
public: public:
int data; int data;
bool is_dummy;
Node* next; Node* next;
std::mutex mut; std::mutex mut;
public: public:
Node(int element);
static Node* Dummy();
void lock(); void lock();
void unlock(); void unlock();
bool is_smaller_than(int n);
bool is_equal(int n);
}; };
Node::Node(int element){
this->data = element;
this->is_dummy = false;
}
Node* Node::Dummy(){
Node* n = new Node(0);
n->is_dummy = true;
return n;
}
bool Node::is_smaller_than(int n) {
// Everything is smaller than a dummy -> false
return this->data < n && !this->is_dummy;
}
bool Node::is_equal(int n) {
// Dummies are not equal to any number -> false
return this->data == n && !this->is_dummy;
}
void Node::lock() { void Node::lock() {
this->mut.lock(); this->mut.lock();
} }