Reputation: 49
I need to make three threads with shared access to linkedlist: searching,adding,removing thread. Seaching thread only browsing through list. Adding threads add item at the end of list and they are mutual exclusive (protected by mutex) but you can searching and adding at the same time. Removing threads remove item from any point at the list and they are mutal exclusive with adding and searching.
My linked list:
struct node
{
int data;
struct node *next;
}
void search(int num)
{
int flag = 0;
struct node *temp;
temp = start;
while(temp!=NULL)
{
if(temp->data == num)
return(temp); //Found
temp = temp->next;
}
if(flag == 0)
return(start); // Not found
}
void insert(int num)
{
int c=0;
struct node *temp;
temp=head;
if(temp==NULL)
{
add(num);
}
else
{
while(temp!=NULL)
{
if(temp->data<num)
c++;
temp=temp->next;
}
if(c==0)
add(num);
else if(c<count())
addafter(num,++c);
else
append(num);
}
}
int delete(int num)
{
struct node *temp, *prev;
temp=head;
while(temp!=NULL)
{
if(temp->data==num)
{
if(temp==head)
{
head=temp->next;
free(temp);
return 1;
}
else
{
prev->next=temp->next;
free(temp);
return 1;
}
}
else
{
prev=temp;
temp= temp->next;
}
}
return 0;
}
If anyone could show me way how to do with threads and mutex I will be so thankful
Upvotes: 3
Views: 5704
Reputation: 800
Assuming you are using pthread.h.
First you should add a struct for you linked list:
typedef struct
{
struct node *first;
pthread_mutex_t list_mutex;
} *List;
And then add pthread_mutex_lock(&list_mutex);
to the start of each function and pthread_mutex_unlock(&list_mutex);
to the end.
Also your functions should receive a List as an argument, so you need to change the function definitions.
You should read about Pthread mutex locks.
Upvotes: 3