qfedu-linux-advanced-level/day7/homework/h6.c

96 lines
2.0 KiB
C

/*
编写一个程序, 创建多个线程, 每个线程负责对一个共享链表进行搜索操作。要求实现线程间的同步, 确保每个线程搜索链表时不会干扰其他线程的工作。
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
typedef struct node
{
char name[32];
struct node *next;
} Node;
Node *head; // 定义头节点
void *find(void *data)
{
int n = 0; // 标识待查询内容在链表中的索引号
char *name = (char *)data;
pthread_mutex_lock(&mutex);
// 查询
Node *p = head->next;
while (p != NULL)
{
if (strcmp(p->name, name) == 0)
{
printf("%s 在链表的索引为 %d\n", name, n);
pthread_mutex_unlock(&mutex);
return NULL;
}
n++;
p = p->next;
}
printf("%s 在链表中未找到\n", name);
pthread_mutex_unlock(&mutex);
return NULL;
}
// 添加节点
void add_node(Node *head, char *name)
{
Node *p = head;
while (p->next != NULL)
p = p->next;
Node *new_node = (Node *)malloc(sizeof(Node));
if (NULL == new_node)
{
perror("malloc error");
return;
}
memset(new_node, 0, sizeof(Node)); // 初始化新节点为默认值
strcpy(new_node->name, name);
p->next = new_node;
}
int main(int argc, char const *argv[])
{
head = (Node *)malloc(sizeof(Node));
if (NULL == head)
{
perror("malloc error");
return 1;
}
memset(head, 0, sizeof(Node));
add_node(head, "a");
add_node(head, "b");
add_node(head, "c");
add_node(head, "d");
// 待查询字符表,包含查询的字符顺序
char *alphabet[4] = {"a", "e", "d", "b"};
pthread_t t[4];
for (int i = 0; i < 4; i++)
{
pthread_create(&t[i], NULL, find, (void *)alphabet[i]);
}
for (int i = 0; i < 4; i++)
{
pthread_join(t[i], NULL);
}
pthread_mutex_destroy(&mutex);
return 0;
}