multithreading - threads safe linked list fine grained in C -
i'm implementing linked list fine grained locking, meaning lock in every node.
when i'm adding new node, want pass 2 arguments: key , value. how can make sure each node has different lock? lock implemented pthread_mutex_t
.
this implementation add:
int setos_add(int key, void* value) { volatile setos_node* node = head; volatile setos_node* prev; pthread_mutex_t new_mutex; //wrong: put same lock //lock head node if(pthread_mutex_lock(&(node->mutex)) == 0){ printf("failed locking\n"); exit(1); } // go through nodes until key of "node" exceeds "key" // new node should between "prev" , "node" while ((node != null) && (node->key < key)) { prev = node; //already locked node = node->next; //locking 2 nodes each time if (node != null){ if(pthread_mutex_lock(&(node->mutex)) == 0){ printf("failed locking\n"); exit(1); } } if (node -> key < key){ //else: need preve staying locked insertions if (pthread_mutex_unlock(&(prev->mutex)) != 0){ printf("failed unlocking\n"); exit(1); } } } // if node same our key - key in list if ((node != null) && (node->key == key)){ if (node != null){ //not end of list if (pthread_mutex_unlock(&(node->mutex)) != 0){ printf("failed unlocking\n"); exit(1); } } if (prev != null){ //not begining of list if (pthread_mutex_unlock(&(prev->mutex)) != 0){ printf("failed unlocking\n"); exit(1); } } return 0; } // allocate new node , initialize setos_node* new_node = (setos_node*) malloc(sizeof(setos_node)); new_node->key = key; new_node->value = value; new_node->mutex = new_mutex; //to change if(pthread_mutex_init(&(new_node-> mutex), null) != 0){ printf("failed init mutex"); exit(1); } // place node list new_node->next = node; prev->next = new_node; if (node != null){ //not end of list if (pthread_mutex_unlock(&(node->mutex)) != 0){ printf("failed unlocking\n"); exit(1); } } if (prev != null){ //not begining of list if (pthread_mutex_unlock(&(prev->mutex)) != 0){ printf("failed unlocking\n"); exit(1); } } return 1; }
you can see in third line i'm defining pthread_mutex_t
node. doing so, each new node have same pthread_mutex_t
?
how can right?
yes same mutex.
you can malloc new mutex element each time need new mutex :
malloc(sizeof(pthread_mutex_t)))
an intialize :
pthread_mutex_init(m, null)
Comments
Post a Comment