-1
我正在尝试为二叉搜索树创建线程安全的删除函数。下面的代码是我的结果,但它会导致程序死锁。发生什么问题?我曾尝试一些评论,但锁导致段错误,而不是...为什么我的线程安全代码不工作?
struct bst_node {
void* data;
pthread_mutex_t mut;
struct bst_node* left;
struct bst_node* right;
};
static void node_del(struct bst_node** node) {
pthread_mutex_lock(&(*node)->mut);
struct bst_node* old_node = *node;
if(((*node)->left == NULL) && ((*node)->right == NULL)) {
*node = NULL;
free_node(old_node);
} else if ((*node)->left == NULL) {
pthread_mutex_lock(&((*node)->right->mut));
*node = (*node)->right;
free_node(old_node);
pthread_mutex_unlock(&(*node)->mut);
} else if ((*node)->right == NULL) {
pthread_mutex_lock(&((*node)->left->mut));
*node = (*node)->left;
free_node(old_node);
pthread_mutex_unlock(&(*node)->mut);
} else {
pthread_mutex_lock(&((*node)->left->mut));
struct bst_node** pred = &(*node)->left;
while ((*pred)->right != NULL) {
pthread_mutex_lock(&(*pred)->right->mut);
pthread_mutex_unlock(&(*pred)->mut);
pred = &(*pred)->right;
}
void* temp = (*pred)->data;
(*pred)->data = (*node)->data;
(*node)->data = temp;
pthread_mutex_unlock(&(*pred)->mut);
node_del(pred);
}
}
请注意,我已经initalized节点和其他功能锁定“MUT”。
您对'free_node()'的调用并不明显被锁定。你可能会在函数中锁定 - 我们无法从这里知道。 –
假设线程't1'锁定了节点'n1'的互斥锁。现在假设线程't2'锁定了节点'n2'的互斥锁。现在,如果't1'尝试访问'n2',当它的互斥锁被锁定时,它将开始等待。同时,'t2'想要使用'n1',但它被't1'锁定。所以,僵局。 –
似乎还有其他一些问题,但我之前评论中的问题也是潜在的僵局。小心这种情况。 –