在C語言中,確保鏈表操作的數據一致性需要采取一定的策略。以下是一些建議:
#include <pthread.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* create_node(int data) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
void insert_node(Node** head, int data) {
Node* new_node = create_node(data);
pthread_mutex_lock(&list_mutex);
new_node->next = *head;
*head = new_node;
pthread_mutex_unlock(&list_mutex);
}
InterlockedCompareExchange
函數來原子地更新鏈表的頭節點。#include <windows.h>
Node* insert_node(Node** head, int data) {
Node* new_node = create_node(data);
Node* old_head = InterlockedCompareExchange(head, new_node, *head);
if (old_head == *head) {
new_node->next = *head;
return new_node;
} else {
// 如果頭節點被其他線程修改,重新嘗試插入操作
return insert_node(head, data);
}
}
#include <pthread.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* create_node(int data) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
void insert_node(Node** head, int data) {
Node* new_node = create_node(data);
pthread_rwlock_wrlock(&list_rwlock);
new_node->next = *head;
*head = new_node;
pthread_rwlock_unlock(&list_rwlock);
}
Node* find_node(Node* head, int data) {
Node* current = head;
while (current != NULL) {
if (current->data == data) {
return current;
}
current = current->next;
}
return NULL;
}
總之,確保C語言鏈表操作的數據一致性需要采取適當的同步策略,如互斥鎖、原子操作和讀寫鎖等。在選擇合適的同步策略時,需要根據程序的實際需求和運行環境進行權衡。