我需要使三个线程具有对链表的共享访问权限:搜索,添加,删除线程。搜寻线程仅浏览列表。添加线程会将项目添加到列表的末尾,并且它们是互斥的(受互斥锁保护),但是您可以同时搜索和添加。删除线程可以从列表中的任何点删除项目,并且它们在添加和搜索中是唯一的。
我的链表:
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;
}
如果有人能告诉我如何使用线程和互斥锁,我将非常感激
假设您正在使用pthread.h。
首先,您应该为链表添加一个结构:
typedef struct
{
struct node *first;
pthread_mutex_t list_mutex;
} *List;
然后添加pthread_mutex_lock(&list_mutex);
到每个函数的开头和pthread_mutex_unlock(&list_mutex);
结尾。
同样,您的函数应该接收一个List作为参数,因此您需要更改函数定义。
您应该阅读有关Pthread互斥锁的信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句