0

trying tom make my linked list implementation in c11 (gcc6), threadsafe. only thing i do not get how many mutex lock and unlocks i should go with?

/**
 * adds a new node to head of the list, alocation of node is done dynamically
 * @param list  address of list
 * @param data pointer to data
 */
void add_head(Linked_list* list, void* data)
{
    Node *node = (Node*) malloc(sizeof(Node));
    //lock
    node->data = data;
    if (list->head == NULL) {
        list->tail = node;
        node->next = NULL;
    } else {
        node->next = list->head;
    }
    list->head = node;
    list->current = node;
    list_size ++;
    //unlock
}

or

/**
 * adds a new node to head of the list, alocation of node is done dynamically
 * @param list  address of list
 * @param data pointer to data
 */
void add_head(Linked_list* list, void* data)
{
    Node *node = (Node*) malloc(sizeof(Node));
    //lock
    node->data = data;
    if ( list->head == NULL ) {
        list->tail = node;
        node->next = NULL;
    } else {
        node->next = list->head;
    }
    //unlock

    //lock
    list->head = node;
    list->current = node;
    list_size ++;
    //unlock
}

or

/**
 * adds a new node to head of the list, alocation of node is done dynamically
 * @param list  address of list
 * @param data pointer to data
 */
void add_head (Linked_list* list, void* data)
{
    Node *node = (Node*) malloc(sizeof(Node));
    //lock
    node->data = data;
    if (list->head == NULL) {
        list->tail = node;
        node->next = NULL;
    } else {
        node->next = list->head;
    }
   //unlock

   //lock
   list->head = node;
   //unlock

   //lock
   list->current = node;
   //unlock

   //lock
   list_size ++;
   //unlock
}

looking for a way to not make other thread wait too much, since i will have many task of tiny time duration read up to 10 bytes from file, change 10 bytes in memory, write 10 bytes file.

Vuong Hoang
  • 149
  • 8
nkvnkv
  • 914
  • 2
  • 12
  • 25

1 Answers1

0

Because you want to support threadsafe for your implementation of function add_head(), you need to guarantee that all shared data accesses have to be atomic.

So I think you should use the first one, i.e use one lock/unlock pair call for whole function implementation.

Vuong Hoang
  • 149
  • 8