diff --git a/src/main/scala/lockfree/Node.scala b/src/main/scala/lockfree/Node.scala index 6e7a84e..790012a 100644 --- a/src/main/scala/lockfree/Node.scala +++ b/src/main/scala/lockfree/Node.scala @@ -1,22 +1,23 @@ + package lockfree abstract class Node(val value: Int, initTail: Option[Node]) { // The type of mutable state held by node. - type State = Option[Node] + type State = (Option[Node], Boolean) //Boolean flag indicates whether THIS has been deleted or not !! not next // The initial mutable state of the node. - def initialState: State = initTail + def initialState: State = (initTail, false); // The atomic variable that holds the state. val atomicState: AbstractAtomicVariable[State] = new AtomicVariable[State](initialState) // Function to read the next node from the state. - def next: Option[Node] = atomicState.get + def next: Option[Node] = atomicState.get._1 // Should return true if the node was marked as deleted. - def deleted: Boolean = false + def deleted: Boolean = atomicState.get._2 // Should mark the node as deleted. - def mark: Boolean = ??? + def mark: Boolean = atomicState.compareAndSet((next, false), (next, true)) } diff --git a/src/main/scala/lockfree/SortedList.scala b/src/main/scala/lockfree/SortedList.scala index c88bd4c..d0c8db3 100644 --- a/src/main/scala/lockfree/SortedList.scala +++ b/src/main/scala/lockfree/SortedList.scala @@ -12,15 +12,43 @@ class SortedList extends AbstractSortedList { // Finds the first node whose value satisfies the predicate. // Returns the predecessor of the node and the node. - def findNodeWithPrev(pred: Int => Boolean): (Node, Option[Node]) = ??? + def findNodeWithPrev(pred: Int => Boolean): (Node, Option[Node]) = { + def findRec(prev : Node, curr : Option[Node]) : (Node, Option[Node]) = { + (prev, curr) match { + case (last, None) => (last, None); + case (_, Some(node)) => + if(node.deleted) { + prev.atomicState.compareAndSet((curr, false), (node.next, false)) + findNodeWithPrev(pred) + }else if(pred(node.value)) (prev, curr) + else findRec(node, node.next) + } + } + findRec(_head, _head.next) + } // Insert an element in the list. - def insert(e: Int): Unit = ??? + def insert(e: Int): Unit = { + val (pred, next) = findNodeWithPrev(_ >= e); + val n = createNode(e, next) + if(!pred.atomicState.compareAndSet((next, false), (Some(n), false))) insert(e) + } // Checks if the list contains an element. - def contains(e: Int): Boolean = ??? + def contains(e: Int): Boolean = { + findNodeWithPrev(_ == e)._2 match { + case None => false + case _ => true; + } + } // Delete an element from the list. // Should only delete one element when multiple occurences are present. - def delete(e: Int): Boolean = ??? + def delete(e: Int): Boolean = { + val (pred, next) = findNodeWithPrev(_ == e) + next match{ + case None => false + case Some(x) => if(x.mark) true else delete(e) + } + } }