gpt4 book ai didi

c++ - 多线程二叉树算法

转载 作者:行者123 更新时间:2023-11-30 02:08:34 25 4
gpt4 key购买 nike

因此,我尝试了一种方法来锁定每个节点,但这需要大量的锁定和解锁……这当然需要相当多的开销。我想知道是否有人知道更有效的算法。这是我的第一次尝试:

typedef struct _treenode{
struct _treenode *leftNode;
struct _treenode *rightNode;
int32_t data;
pthread_mutex_t mutex;
}TreeNode;

pthread_mutex_t _initMutex = PTHREAD_MUTEX_INITIALIZER;

int32_t insertNode(TreeNode **_trunk, int32_t data){
TreeNode **current;
pthread_mutex_t *parentMutex = NULL, *currentMutex = &_initMutex;

if(_trunk != NULL){
current = _trunk;
while(*current != NULL){
pthread_mutex_lock(&(*current)->mutex);
currentMutex = &(*current)->mutex;
if((*current)->data < data){
if(parentMutex != NULL)
pthread_mutex_unlock(parentMutex);
pthreadMutex = currentMutex;
current = &(*current)->rightNode;
}else if((*current)->data > data){
if(parentMutex != NULL)
pthread_mutex_unlock(parentMutex);
parentMutex = currentMutex;
current = &(*current)->leftNode;
}else{
pthread_mutex_unlock(currentMutex);
if(parentMutex != NULL)
pthread_mutex_unlock(parentMutex);
return 0;
}
}
*current = malloc(sizeof(TreeNode));
pthread_mutex_init(&(*current)->mutex, NULL);
pthread_mutex_lock(&(*current)->mutex);
(*current)->leftNode = NULL;
(*current)->rightNode = NULL;
(*current)->data = data;
pthread_mutex_unlock(&(*current)->mutex);
pthread_mutex_unlock(currentMutex);
}else{
return 1;
}
return 0;
}

int main(){
int i;
TreeNode *trunk = NULL;
for(i=0; i<1000000; i++){
insertNode(&trunk, rand() % 50000);
}
}

最佳答案

您不需要锁定您访问的每个节点。你可以这样做。当您要进行插入时锁定节点。做你的插入和解锁。如果另一个线程碰巧需要在它的同一点插入并且节点被锁定,它应该在进一步向下遍历之前等待。一旦节点解锁,它就可以继续遍历树的更新部分。

关于c++ - 多线程二叉树算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6506513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com