OiO.lk Blog C# How to solve the problem of multi-TASK operation linked list
C#

How to solve the problem of multi-TASK operation linked list


The code runs in a real-time operating system. The execution of a low-priority task can be interrupted by a high-priority task. At this time, the low-priority task continues to execute after the high-priority task ends.

The code defines some linked list processing functions, among which TASK1 calls dp_mem_list_get_and_delete_first and TASK2 calls dp_mem_list_add_at_tail.

The problem is that both functions read or write the same variable, for example, dp_mem_list_get_and_delete_first writes list->tail, while dp_mem_list_add_at_tail reads and writes list->tail.

This will cause an error when the TASK is preempted. Online information suggests using locks or semaphores, but the project requires that locks or semaphores cannot be used. How can I solve this problem?

Thanks in advance.

typedef unsigned int  uint32;

#define NULL    0

typedef struct T_DP_MEM_LIST_NODE_TAG
{
    struct T_DP_MEM_LIST_NODE_TAG *next;
}T_DP_MEM_LIST_NODE;

typedef struct mem_list
{
    T_DP_MEM_LIST_NODE  *head;
    T_DP_MEM_LIST_NODE  *tail;
    uint32              alloc_num;
    uint32              free_num;
}T_DP_MEM_LIST_HEAD_NODE;

void dp_mem_list_init(T_DP_MEM_LIST_HEAD_NODE *list)
{
    list->head = NULL;
    list->tail = NULL;
    list->alloc_num = 0;
    list->free_num  = 0;
}

T_DP_MEM_LIST_NODE* dp_mem_list_get_and_delete_first
(
    T_DP_MEM_LIST_HEAD_NODE *list
)
{
    T_DP_MEM_LIST_NODE *return_node = NULL;

    if (list->head != NULL)
    {
        return_node = list->head;

        list->head = list->head->next;

        if (list->head == NULL)
        {
            list->tail = NULL;
        }

        return_node->next = NULL;

        list->alloc_num++;        
    }    
}

void dp_mem_list_add_at_tail
(
    T_DP_MEM_LIST_NODE      *new_node,
    T_DP_MEM_LIST_HEAD_NODE *list
)
{
    if (list->tail != NULL)
    {
        list->tail->next = new_node;
    }
    else
    {
        list->head = new_node;
    }
    
    list->tail = new_node;
    new_node->next = NULL;

    list->free_num++;
}



You need to sign in to view this answers

Exit mobile version