【问题标题】:threadsafe code with mutex带有互斥锁的线程安全代码
【发布时间】:2016-06-26 00:28:05
【问题描述】:

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

【问题讨论】:

    标签: linked-list pthreads mutex gcc6


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多