我需要创建三个具有共享链接列表访问权限的线程:搜索、添加、删除线程。只在列表中搜索线程。添加线程在列表末尾添加项,它们是互斥的(由互斥保护),但是可以同时搜索和添加。删除线程从列表中的任何点移除项,并且它们与添加和搜索是互斥的。
我的链接列表:
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;
}如果有人能告诉我如何处理线程和互斥对象,我会非常感激的。
发布于 2016-12-19 11:27:14
假设您使用的是pthread.h。
首先,应该为链接列表添加一个结构:
typedef struct
{
struct node *first;
pthread_mutex_t list_mutex;
} *List;然后将pthread_mutex_lock(&list_mutex);添加到每个函数的开头,pthread_mutex_unlock(&list_mutex);添加到末尾。
此外,您的函数应该接收一个作为参数的列表,因此您需要更改函数定义。
你应该读一读关于多线程互斥锁的文章。
https://stackoverflow.com/questions/41220848
复制相似问题