2016-06-26 9 views
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 
} 

または

私は小さな継続時間の多くのタスクは、10まで読まなければならないので、他のスレッドは、あまり待たせるしないようにする方法を探して
/** 
* 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バイトのファイルの書き込み。

答えて

0

add_head()の実装にthreadsafeをサポートしたいので、すべての共有データアクセスがアトミックであることを保証する必要があります。

だから、私はあなたが最初のものを使うべきだと思います。すなわち、関数の実装全体に対して1つのロック/ロック解除ペア呼び出しを使用する必要があります。

関連する問題