0

试图汤姆在 c11 (gcc6) 中实现我的链表,线程安全。唯一我没有得到多少互斥锁和解锁我应该去?

/**
 * 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
}

或者

/**
 * 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
}

或者

/**
 * 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
}

寻找一种不让其他线程等待太多的方法,因为我将有许多持续时间很短的任务从文件中读取最多 10 个字节,更改内存中的 10 个字节,写入 10 个字节的文件。

4

1 回答 1

0

因为您想支持threadsafe您的功能实现add_head(),所以您需要保证所有共享数据访问必须是原子的。

所以我认为你应该使用第一个,即使用一个锁定/解锁对调用来实现整个功能。

于 2016-06-27T03:39:28.750 回答