I am learning to write a multi-threaded linked list class implementation with basic functionality such as push
to front or back, pop_back
and read
. I came up with this implementation:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex m;
template<class T>
class Node{
public:
T data;
Node* next;
Node(T data):data(data),next(NULL){}
};
template<class T>
class List{
Node<T> *head;
public:
List():head(NULL){}
List(const List<T>&)=default; //default copy constructor
List& operator =(const List<T>&)=default; //default assignment
List(List<T>&&)=default; //default move constructor
List& operator =(List<T>&&)=default; //default move assignment
void push_front(T val){ //push data to front
std::lock_guard<std::mutex> lock(m);
Node<T>* temp=new Node<T>(val);
if(head==NULL)
head=temp;
else{
temp->next=head;
head=temp;
}
}
void pop_back(){ //pop from back
std::lock_guard<std::mutex> lock(m);
Node<T>* cur=head;
while(cur->next->next)
cur = cur->next;
Node<T>* temp=cur->next;
delete(temp);
cur->next=NULL;
}
T front(){ //return front of Linkedlist
if(head!=NULL)
return head->data;
return -1;
}
void push_back(T val){ //push at back
std::lock_guard<std::mutex> lock(m);
Node<T>* temp=new Node<T>(val);
if(head==NULL)
head=temp;
else{
Node<T>* cur=head;
while(cur->next)
cur = cur->next;
cur->next=temp;
}
}
int size(){ //return size
int size=0;
Node<T>* cur=head;
while(cur){
size++;
cur=cur->next;
}
return size;
}
void display(){ //read from linked list
std::lock_guard<std::mutex> lock(m);
Node<T>* cur=head;
while(cur){
std::cout<<cur->data<<" ";
cur = cur->next;
}
std::cout<<"\n";
}
~List(){
Node<T>* current = head;
Node<T>* next;
while (current != NULL) {
next = current->next;
delete current;
current = next;
}
}
};
But, I am not very sure if I covered it right. Please share some opinions on how to make it perfect. Also, I am targeting C++11, so please throw some pointers/suggestions in that area also.
In particular, I am looking for is answers to these questions:
- Is this a correct approach for acquiring mutex in
push()
anddisplay()
, in a multi-threaded environment? How can I prioritize the read/delete/write operations. For example, suppose 1 thread is displaying the data and another thread comes which wants to pop_back from the data. How do I make the changes so that my 2nd thread gets the priority while 1st thread was using my node.- I have not much worked with C++11 — I just started it few months ago — so I would like to know what more I should have in my class.
- In case there are any possible bugs in this code, please let me know that too.