线程安全代码与互斥锁

时间:2016-06-26 00:28:05

标签: linked-list pthreads mutex gcc6

尝试tom在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个字节的文件。

1 个答案:

答案 0 :(得分:0)

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

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