链接列表示例使用线程

时间:2010-06-03 00:37:53

标签: winapi multithreading synchronization linked-list

在使用多个线程来扩展链表时,我已经阅读了以下使用CRITICAL_SECTION的代码。什么是main()部分,它使用两个线程添加到链表?

#include <windows.h>

typedef struct _Node
{
    struct _Node *next;
    int data;
} Node;

typedef struct _List
{
    Node *head;
    CRITICAL_SECTION critical_sec;
} List;

List *CreateList()
{
    List *pList = (List*)malloc(sizeof(pList));
    pList->head = NULL;
    InitializeCriticalSection(&pList->critical_sec);
    return pList;
}

void AddHead(List *pList, Node *node)
{
    EnterCriticalSection(&pList->critical_sec);
    node->next = pList->head;
    pList->head = node;
    LeaveCriticalSection(&pList->critical_sec);
}

void Insert(List *pList, Node *afterNode, Node *newNode)
{
    EnterCriticalSection(&pList->critical_sec);
    if (afterNode == NULL)
    {
        AddHead(pList, newNode);
    }
    else
    {
        newNode->next = afterNode->next;
        afterNode->next = newNode;
    }
    LeaveCriticalSection(&pList->critical_sec);
}

Node *Next(List *pList, Node *node)
{
    Node* next;
    EnterCriticalSection(&pList->critical_sec);
    next = node->next;
    LeaveCriticalSection(&pList->critical_sec);
    return next;
}

1 个答案:

答案 0 :(得分:0)

可能会涉及对CreateThread

的一次或多次调用