Linked list example using threads
Posted
by Carl_1789
on Stack Overflow
See other posts from Stack Overflow
or by Carl_1789
Published on 2010-06-03T00:37:52Z
Indexed on
2010/06/03
0:44 UTC
Read the original article
Hit count: 272
I have read the following code of using CRITICAL_SECTION
when working with multiple threads to grow a linked list. what would be the main() part which uses two threads to add to linked list?
#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;
}
© Stack Overflow or respective owner