Introduction
Most of you know how to implement a Single Linked List. Not so many know how
to make a template out of it. Even less know how to make it thread safe. Of
course, not all application need Thread Safe Single Link List. Application like
notepad, calculator or ping. Hmmm... still...
Anyway, lists and thread safe,
are two things that go hand in hand when developing... any kind of application.
By making any list thread safe you avoid a lot of problems. Problems which are
not easy to trace using a debugger.
...and if all this comes as a template... even better.
All
this being said, let's get to the point.
Using the code
First add everything that's in the pack to your project: LinkedListSingle.h
,
LinkedListSingle.cpp
, NamedCriticalSection.h
, NamedCriticalSection.cpp
,
SpinLock.h
, SpinLock.cpp
, DebugTrace.h
and DebugTrace.cpp
.
Second, include
this where you need to declare a new list:
#include "LinkedListSingle.h"
#include "LinkedListSingle.cpp" // you need this too, or the code for the list will not be generated!!!
Once you did all this, declare a new list, like this:
CLinkedListSingle<int, sinzeof(int)> IntegerList;
The template can be used with anything... so, let's complicate the things a
bit. Let's say we have this class:
class SomeClass
{
double DVar;
public:
char szString[ 32 ];
SomeClass(): DVar( 0 ) { memset( szString, 0, 32 ); };
~SomeClass(){};
void Increase( void ){ DVar++; };
}
Now, you want a list of SomeClass
elements. You declare it like this:
CLinkedListSingle<SomeClass, sinzeof(SomeClass)> SomeClassList;
CLinkedListSingle
It's not a complex class... once you get to know it:).
template <class T, int i>
class CLinkedListSingle
{
CDebugTrace Trace;
USHORT Size;
public:
CLinkedListSingleNode< T, i > *pHead;
CNamedCriticalSection Section;
CLinkedListSingle();
~CLinkedListSingle();
bool Initialize();
bool Free();
bool Add(T&);
bool Remove(T&);
bool Remove(USHORT);
bool Insert(USHORT, T&);
USHORT GetSize(void);
};
Normally this should not interest you. This class is made to just "set it and
use it".
One more thing. If you ever need to directly access the elements of
the list - let's say you need to "walk" through all the elements and do
something - remember to do this:
CLinkedListSingle<SomeClass, sinzeof(SomeClass)> SomeClassList;
CSpinLock Spin( &(SomeClass.Section), "NoWhere" );
if( Spin.Lock() )
{
...
Spin.Unlock();
}
Points of Interest
Anything involving linked lists. This article refers only to Single Link
List, but should not be hard for you to create a Double Link List out of it. I
hope soon I will be able to post a new article about it.
History
version 1.0 - 27-february-2005 - So, now it's history!:)