多核计算与程序设计 - 05 基本算法和数据结构 之二 多线程链表

链表是数据结构中的基础知识,这里不做详细说明。这里说的多线程链表主要是对链表的访问加了一些互斥等访问控制,使多线程可以安全的访问链表。

多线程链表中有锁,用来保障线程对队列的访问时的互斥性。


此程序运行在 Red Hat Linux上, 使用 pthread 库。

#include <pthread.h>


#ifndef __MT_LIST_H__
#define __MT_LIST_H__

typedef struct _DLIST_NODE_st
{
    struct _DLIST_NODE_st *m_pNext;
    struct _DLIST_NODE_st *m_pPrev;
    void                  *m_pData;
} DLIST_NODE_st;

typedef struct _DList_st
{
    DLIST_NODE_st* m_pHead;
    DLIST_NODE_st* m_pTail;
    DLIST_NODE_st* m_pCurr;
    unsigned int   m_uCount;
} DList_st;


typedef struct _MTList_st
{
    DList_st  *m_List;
    <span style="color:#ff0000;">pthread_mutex_t  m_Lock;</span>

} MTList_st;



class MT_DList
{
public:
    MT_DList();

    int   PushHead(void *pData);
    int   PushTail(void *pData);
    void* PopHead();
    void* PopTail();
    ~MT_DList();
private:
    MTList_st * m_pList;
};


#endif

在运行 Push 和 Pop的过程中都会对锁进行操作,从而保证多线程访问队列的安全性。

完整源代码下载


测试结果:

Create MT_DList
PushHead push pre_lock
PushHead push un_lock
Push Msg 0
 
pop Tail locking
pop Tail unlocking
Pop Msg 0
 
PushHead push pre_lock
PushHead push un_lock
Push Msg 1
 
pop Tail locking
pop Tail unlocking
Pop Msg 1
 
PushHead push pre_lock
PushHead push un_lock
Push Msg 2
 
pop Tail locking
pop Tail unlocking
Pop Msg 2
 
PushHead push pre_lock
PushHead push un_lock
Push Msg 3
 
PushHead push pre_lock
PushHead push un_lock
Push Msg 4
 
pop Tail locking
pop Tail unlocking
Pop Msg 3
 
PushHead push pre_lock
PushHead push un_lock
Push Msg 5
 
pop Tail locking
pop Tail unlocking
Pop Msg 4
 
PushHead push pre_lock
PushHead push un_lock
Push Msg 6
 
PushHead push pre_lock
PushHead push un_lock
Push Msg 7
 
pop Tail locking
pop Tail unlocking
Pop Msg 5
 
PushHead push pre_lock
PushHead push un_lock
Push Msg 8
 
pop Tail locking
pop Tail unlocking
Pop Msg 6
 
PushHead push pre_lock
PushHead push un_lock
Push Msg 9
 
pop Tail locking
pop Tail unlocking
Pop Msg 7
 
pop Tail locking
pop Tail unlocking
Pop Msg 8
 
pop Tail locking
pop Tail unlocking
Pop Msg 9



你可能感兴趣的:(多核计算与程序设计 - 05 基本算法和数据结构 之二 多线程链表)