带有静音的ThreadSafe代码



尝试汤姆在c11(gcc6),threadsafe中实现我的链接列表。我唯一没有得到多少个静音锁,我应该使用多少个?

/**
 * 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个字节文件。

<</p>

因为您想支持threadsafe用于实现函数add_head(),因此您需要确保所有共享数据访问都必须是原子。

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

相关内容

  • 没有找到相关文章

最新更新