65.9K
CodeProject 正在变化。 阅读更多。
Home

Hardwired 的线程安全单向链表模板

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.14/5 (10投票s)

2005年2月26日

2分钟阅读

viewsIcon

45335

downloadIcon

439

本文介绍了如何使用 CLinkedListSingle 模板类。此模板是单链表的线程安全实现。

引言

你们大多数人都知道如何实现一个单链表。很少有人知道如何从中创建一个模板。更少人知道如何使其线程安全。当然,并非所有应用程序都需要线程安全的单链表。像记事本、计算器或 ping 这样的应用程序。 呃... 还是...

无论如何,列表和线程安全是开发任何类型应用程序时密不可分的两件事。通过使任何列表线程安全,您可以避免很多问题。使用调试器不容易追踪这些问题。

...如果这一切都作为模板出现...那就更好了。

综上所述,让我们进入正题。

使用代码

首先将包中的所有内容添加到您的项目中:LinkedListSingle.hLinkedListSingle.cppNamedCriticalSection.hNamedCriticalSection.cppSpinLock.hSpinLock.cppDebugTrace.hDebugTrace.cpp

其次,在您需要声明新列表的地方包含这个。

#include "LinkedListSingle.h"
#include "LinkedListSingle.cpp"    // you need this too, or the code for the list will not be generated!!!

完成所有操作后,声明一个新列表,如下所示

//
// somewhere in your application:
//

CLinkedListSingle<int, sinzeof(int)>    IntegerList;

该模板可以与任何东西一起使用...所以,让我们稍微复杂化一下。 假设我们有这个类

//
// some class
//

class SomeClass
{
    double        DVar;    // a double private data member

public:

    char        szString[ 32 ];    // a string public data member

    SomeClass(): DVar( 0 )    { memset( szString, 0, 32 ); };
    ~SomeClass(){};

    void    Increase( void ){ DVar++; };    
}

现在,您需要一个 SomeClass 元素的列表。 你这样声明它

//
// somewhere in your application:
//

CLinkedListSingle<SomeClass, sinzeof(SomeClass)>    SomeClassList;

CLinkedListSingle

它不是一个复杂的类...一旦你了解它 :)

template <class T, int i> 
class CLinkedListSingle
{
    CDebugTrace    Trace;        // used for debugging

    USHORT        Size;        // size of list

public:
    CLinkedListSingleNode< T, i >    *pHead;        // head of list
    CNamedCriticalSection        Section;    // critical section object used to lock the list
                            // this way using the list in a thread safe manner

    CLinkedListSingle();
    ~CLinkedListSingle();

    bool Initialize();        // initialize the list
    bool Free();            // release all elements of the list

    bool Add(T&);            // add new element to the head of list
    bool Remove(T&);        // remove element - by content
    bool Remove(USHORT);        // remove element - by position
    bool Insert(USHORT, T&);    // insert element in list

    USHORT GetSize(void);        // get the size of list
};

通常这不应该引起您的兴趣。 此类旨在仅“设置并使用它”。

还有一件事。 如果您需要直接访问列表的元素 - 假设您需要“遍历”所有元素并执行某些操作 - 请记住这样做

//
// somewhere in your application:
//

CLinkedListSingle<SomeClass, sinzeof(SomeClass)>    SomeClassList;
//
// somewhere else in your application (different thread for example)
//

CSpinLock    Spin( &(SomeClass.Section), "NoWhere" );
if( Spin.Lock() )
{
    //
    // direct access over list and elements data
    //
    
    ...

    Spin.Unlock();
}

关注点

任何涉及链表的东西。 本文仅指单链表,但您应该不难从中创建双链表。 我希望很快我将能够发布一篇关于它的新文章。

历史

版本 1.0 - 2005 年 2 月 27 日 - 所以,现在这是历史了! :)

© . All rights reserved.