Concurrent Binary Search Tree Implementation in C++

Introduction

This article presents a concurrent binary search tree implementation in C++, designed to be concise and easy to understand. We will discuss the interface definition, followed by the implementation of concurrent search, insert, delete, and update operations. Finally, we will provide an example of executing these operations concurrently. Binary search trees (BSTs) are a widely used data structure due to their efficient search, insertion, and deletion capabilities. A BST is a tree-like data structure where each node has at most two children, and for all nodes, the left child node is less than the parent node, and the right child node is greater than the parent node.

The time complexity for search, insert, and delete operations is generally O(h), where h is the height of the tree. In a balanced tree, the height is O(log n), where n is the number of nodes. In concurrent programming, multiple threads execute simultaneously, and concurrent access to shared data structures, such as a binary search tree, can lead to unpredictable results if not handled correctly. A concurrent binary search tree ensures that these operations are thread-safe, allowing multiple threads to access and modify the tree without causing data corruption or race conditions.

Concurrent Binary Search Tree Implementation in C++

Concurrent Binary Search Tree C++ Interface Definition

To implement a concurrent binary search tree in C++, we first define a template class ConcurrentBinarySearchTree with a type parameter T that supports the less-than operator. This constraint ensures that the items stored in the tree can be compared, which is a fundamental requirement for the operations of a binary search tree. The class exposes four main methods: search, insert, delete, and update.

#include <memory>
#include <mutex>

using std::unique_ptr;
using std::mutex;

template <typename T>
class ConcurrentBinarySearchTree {
public:
    bool search(const T& item) const;
    bool insert(const T& item);
    bool remove(const T& item);
    bool update(const T& oldItem, const T& newItem);

private:
    struct Node {
        T value;
        unique_ptr<Node> left;
        unique_ptr<Node> right;
    };

    unique_ptr<Node> root;
    mutable mutex mtx;
};
  • The search operation checks if an item exists within the tree and returns true if found, otherwise false. The time complexity of the search operation is O(h), where h is the height of the tree.
  • The insert operation adds a new item to the tree while maintaining the binary search tree property. The time complexity of the insert operation is O(h), where h is the height of the tree.
  • The delete operation removes an item from the tree and rearranges the tree to maintain its properties. The time complexity of the delete operation is O(h), where h is the height of the tree.
  • The update operation updates an existing item in the tree with a new item while maintaining the binary search tree property. The time complexity of the update operation is O(h), where h is the height of the tree.

The next sections of this article will explain the concurrent implementations of these operations, ensuring thread-safety and efficient performance while maintaining the binary search tree properties.

Concurrent Search Operation Implementation in Binary Search Tree

The concurrent search operation allows multiple threads to search for items within the binary search tree simultaneously without causing data corruption. The search operation does not modify the tree structure, so thread-safety is achieved without the need for locks or other synchronization mechanisms.

In the search operation, we traverse the tree, starting from the root node, comparing the target item with each node’s value. If the target item is less than the current node’s value, we move to the left child; otherwise, we move to the right child. Whenever we reach a null reference, the item is not in the tree, and we return false. If we find a node with the same value as the target item, we return true. The time complexity of the search operation is O(h), where h is the height of the tree. In the worst case, we need to traverse the entire height of the tree.

template <typename T>
bool ConcurrentBinarySearchTree<T>::search(const T& item) const {
    // Traverses the tree, comparing each node's value with the target item.
    // If found, it returns true. Otherwise, it returns false.
    const Node* current = root.get();

    while (current != nullptr) {
        if (item == current->value) {
            return true;
        }
        current = (item < current->value) ? current->left.get() : current->right.get();
    }

    return false;
}

Concurrent Insert Operation Implementation in Binary Search Tree

The concurrent insert operation adds a new item to the tree while maintaining the binary search tree property. To ensure thread-safety, we use a lock_guard to lock the mutex when modifying the tree structure. This prevents multiple threads from inserting nodes simultaneously, which could lead to data corruption.

In the insert operation, we traverse the tree to find the position for the new item. We compare the new item with each node’s value during the traversal. If the new item is less than the current node’s value, we move to the left child; otherwise, we move to the right child. If we find a node with the same value as the new item, the insertion is a duplicate, and we return false. Once we reach a null reference, we have found the position for the new item. We then lock the tree to prevent other threads from modifying it while we insert the new node. The time complexity of the insert operation is O(h), where h is the height of the tree.

template <typename T>
bool ConcurrentBinarySearchTree<T>::insert(const T& item) {
    // Inserts a new node by finding its position in the tree.
    // Uses a lock_guard to ensure thread-safety during the process.
    std::unique_lock<std::mutex> lock(mtx);
    Node* parent = nullptr;
    Node* current = root.get();

    while (current != nullptr) {
        parent = current;
        if (item == current->value) {
            return false;
        }
        current = (item < current->value) ? current->left.get() : current->right.get();
    }

    std::unique_ptr<Node> newNode = std::make_unique<Node>();
    newNode->value = item;
    newNode->left = nullptr;
    newNode->right = nullptr;

    if (parent == nullptr) {
        root = std::move(newNode);
    } else if (item < parent->value) {
        parent->left = std::move(newNode);
    } else {
        parent->right = std::move(newNode);
    }

    return true;
}

Concurrent Delete Operation Implementation

The concurrent delete operation removes an item from the tree and rearranges the tree to maintain the binary search tree property. To ensure thread-safety, we use a lock_guard to lock the mutex when modifying the tree structure. The delete operation involves three main scenarios:

  1. The node to delete has no children: In this case, we simply remove the node from the tree and update its parent’s reference.
  2. The node to delete has one child: We remove the node from the tree and update its parent’s reference to point to the node’s single child.
  3. The node to delete has two children: We find the node with the minimum value in the right subtree (the inorder successor), replace the node to delete with the inorder successor’s value, and then delete the inorder successor.

The time complexity of the delete operation is O(h), where h is the height of the tree.

template <typename T>
bool ConcurrentBinarySearchTree<T>::deleteItem(const T& item) {
    // Deletes an item from the tree and handles three scenarios:
    // 1. The node has no children.
    // 2. The node has one child.
    // 3. The node has two children.
    // Uses a lock_guard to ensure thread-safety during the process.
    std::unique_lock<std::mutex> lock(mtx);
    Node* parent = nullptr;
    Node* current = root.get();

    while (current != nullptr && current->value != item) {
        parent = current;
        current = (item < current->value) ? current->left.get() : current->right.get();
    }

    if (current == nullptr) {
        return false;
    }

    // Case 1: Node with no children
    if (current->left == nullptr && current->right == nullptr) {
        deleteNode(parent, current);
    }
    // Case 2: Node with one child
    else if (current->left == nullptr || current->right == nullptr) {
        Node* child = (current->left != nullptr) ? current->left.get() : current->right.get();
        deleteNode(parent, current, child);
    }
    // Case 3: Node with two children
    else {
        Node* inorderSuccessorParent = current;
        Node* inorderSuccessor = current->right.get();
        while (inorderSuccessor->left != nullptr) {
            inorderSuccessorParent = inorderSuccessor;
            inorderSuccessor = inorderSuccessor->left.get();
        }
        current->value = inorderSuccessor->value;
        deleteNode(inorderSuccessorParent, inorderSuccessor);
    }

    return true;
}

Concurrent Update Operation Implementation

The concurrent update operation updates an existing item in the tree with a new item while maintaining the binary search tree property. To ensure thread-safety, we use a lock_guard to lock the mutex when modifying the tree structure. In the update operation, we first delete the old item from the tree, and then insert the new item. By using a lock_guard, we ensure that no other thread can modify the tree between the delete and insert operations. The time complexity of the update operation is O(h), where h is the height of the tree. Since the update operation involves a delete followed by an insert, the complexity remains the same as individual delete and insert operations.

template <typename T>
bool ConcurrentBinarySearchTree<T>::update(const T& oldItem, const T& newItem) {
    // Updates a node by deleting the old item and inserting the new one.
    // Uses a lock_guard to ensure thread-safety.
    std::unique_lock<std::mutex> lock(mtx);
    if (deleteItem(oldItem)) {
        return insert(newItem);
    }

    return false;
}

Testing the Concurrent Binary Search Tree

#include <iostream>
#include <thread>
#include <vector>

void insertElements(ConcurrentBinarySearchTree<int>& tree, int start, int end) {
    for (int i = start; i <= end; ++i) {
        tree.insert(i);
    }
}

void deleteElements(ConcurrentBinarySearchTree<int>& tree, int start, int end) {
    for (int i = start; i <= end; ++i) {
        tree.deleteItem(i);
    }
}

void updateElements(ConcurrentBinarySearchTree<int>& tree, int start, int end, int offset) {
    for (int i = start; i <= end; ++i) {
tree.update(i, i + offset);
}
}

int main() {
ConcurrentBinarySearchTree<int> tree;
int elementCount = 50000;

// Concurrent insertions
std::thread insertThread1(insertElements, std::ref(tree), 1, elementCount / 2);
std::thread insertThread2(insertElements, std::ref(tree), elementCount / 2 + 1, elementCount);

// Concurrent deletions
std::thread deleteThread1(deleteElements, std::ref(tree), 1, elementCount / 4);
std::thread deleteThread2(deleteElements, std::ref(tree), elementCount / 4 + 1, elementCount / 2);

// Concurrent updates
std::thread updateThread1(updateElements, std::ref(tree), 1, elementCount / 4, elementCount);
std::thread updateThread2(updateElements, std::ref(tree), elementCount / 4 + 1, elementCount / 2, elementCount);

insertThread1.join();
insertThread2.join();
deleteThread1.join();
deleteThread2.join();
updateThread1.join();
updateThread2.join();

std::cout << "Processing completed." << std::endl;

return 0;
}

Conclusion

In conclusion, this article presented a concurrent binary search tree implementation in C++, designed to be clear and easy to understand. We discussed the class definition and provided a thread-safe implementation of concurrent search, insert, delete, and update operations while maintaining the binary search tree properties. By using a combination of mutexes, lock_guards, and careful consideration of the areas that require synchronization, we achieved an efficient and safe manipulation of the data structure in a multi-threaded environment. The concurrent binary search tree offers time complexities of O(h) for each operation, where h is the height of the tree, making it a valuable data structure for use in concurrent programming scenarios.

Correlated Resources

Tags: No tags

Comments are closed.