Interlocked、InterlockedExchangePointer原子访问系列函数

原文:http://blog.csdn.net/ace1985/article/details/5729912


所谓原子访问,指的是一个线程在访问某个资源的同时能够保证没有其他线程会在同一时刻访问同一资源。Interlocked系列函数提供了这样的操作。所有这些函数会以原子方式来操控一个值。

Interlocked函数的工作原理取决于代码运行的CPU平台,如果是x86系列CPU,那么Interlocked函数会在总线上维持一个硬件信号,这个信号会阻止其他CPU访问同一个内存地址。我们必须确保传给这些函数的变量地址是经过对齐的,否则这些函数可能会失败。C运行库提供了一个_aligned_malloc函数,我们可以使用这个函数来分配一块对齐过的内存:

void * _aligned_malloc(

    size_tsize,  //要分配的字节数

    size_talignment //要对齐到的字节边界,传给alignment的值必须是2的整数幂次方

);

Interlocked函数的另一个需要注意的点是它们执行得很快。调用一次Interlocked函数通常只占用几个CPU周期(通常小于50),而且不需要在用户模式和内核模式之间进行切换(这个切换通常需要占用1000CPU周期以上)。

 

1)原子加减操作InterlockedExchangeAdd函数原型如下:

LONG __cdecl InterlockedExchangeAdd( //32位值进行操作

  __inout  LONG volatile *Addend, //需要递增的变量地址

  __in     LONGValue //增量值,可为负值表示减法

);

 

LONGLONG __cdecl InterlockedExchangeAdd64//64位值进行操作

  __inout  LONGLONG volatile *Addend,

  __in     LONGLONGValue

);

 

2InterlockedExchange函数用于原子地将32位整数设为指定的值:

LONG __cdecl InterlockedExchange(

  __inout  LONG volatile *Target, //指向要替换的32位值的指针

  __in     LONGValue //替换的值

);

返回值是指向原先的32位整数值。

 

InterlockedExchangePointer函数原子地用于替换地址值:

PVOID __cdecl InterlockedExchangePointer(

  __inout  PVOID volatile *Target, //指向要替换的地址值的指针

  __in     PVOIDValue //替换的地址值

);

返回值是原来的地址值。

32位应用程序来说,以上两个函数都用一个32位值替换另一个32位值,但对64位应用程序来说,InterlockedExchange替换的是32位值,而InterlockedExchangePointer替换的是64位值。

 

当然,还有一个函数InterlockedExchange64专门用来原子地操作64位值的:

LONGLONG __cdecl InterlockedExchange64(

  __inout  LONGLONG volatile *Target,

  __in     LONGLONGValue

);

 

在实现旋转锁时,InterlockedExchange函数极其有用:

//标识一个共享资源是否正在被使用的全局变量

BOOLg_fResourceInUse = FALSE;

...

void ASCEFunc()

{

         //等待访问共享资源

         while(InterlockedExchange(&g_fResourceInUse,TRUE) == TRUE)

                   sleep(0);

         //访问共享资源

         ...

         //结束访问

         InterlockedExchange(&g_fResourceInUse,FALSE);

}

注意,在使用这项技术时要小心,因为旋转锁会耗费CPU时间。特别是在单CPU机器上应该避免使用旋转锁,如果一个线程不停地循环,那么这会浪费宝贵的CPU时间,而且会阻止其他线程改变该锁的值。

 

3)函数InterlockedCompareExchange函数和InterlockedCompareExchangePointer函数原型如下:

LONG __cdecl InterlockedCompareExchange(

  __inout  LONG volatile *Destination, //当前值

  __in     LONGExchange, //

  __in     LONGComparand //比较值

);

PVOID __cdecl InterlockedCompareExchangePointer(

  __inout  PVOID volatile *Destination,

  __in     PVOIDExchange,

  __in     PVOIDComparand

);

这两个函数以原子方式执行一个测试和设置操作。对32位应用程序来说,这两个函数都对32位值进行操作;在64位应用程序中,InterlockedCompareExchange32位值进行操作而InterlockedCompareExchangePointer64位值进行操作。函数会将当前值(Destination指向的)与参数Comparand进行比较,如果两个值相同,那么函数会将*Destination修改为Exchange参数指定的值。若不等,则*Destination保持不变。函数会返回*Destination原来的值。所有这些操作都是一个原子执行单元来完成的。

当然,这两个函数的64位版本是:

LONGLONG __cdecl InterlockedCompareExchange64(

  __inout  LONGLONG volatile *Destination,

  __in     LONGLONGExchange,

  __in     LONGLONGComparand

);

 

4Interlocked单向链表函数

InitializeSListHead函数用于创建一个空的单向链表栈:

void WINAPIInitializeSListHead(

  __inout  PSLIST_HEADERListHead

);

 

InterlockedPushEntrySList函数在栈顶添加一个元素:

PSLIST_ENTRYWINAPI InterlockedPushEntrySList(

  __inout  PSLIST_HEADERListHead,

  __inout  PSLIST_ENTRYListEntry

);

 

InterlockedPopEntrySList函数移除位于栈顶的元素并将其返回:

PSLIST_ENTRYWINAPI InterlockedPopEntrySList(

  __inout  PSLIST_HEADERListHead

);

 

InterlockedFlushSList函数用于清空单向链表栈:

PSLIST_ENTRYWINAPI InterlockedFlushSList(

  __inout  PSLIST_HEADERListHead

);

 

QueryDepthSList函数用于返回栈中元素的数量:

USHORT WINAPIQueryDepthSList(

  __in  PSLIST_HEADERListHead

);

 

单向链表栈中元素的结构是:

typedef struct _SLIST_ENTRY {

  struct _SLIST_ENTRY *Next;

} SLIST_ENTRY,*PSLIST_ENTRY;

注意:所有单向链表栈中的元素必须以MEMORY_ALLOCATION_ALIGNMENT方式对齐,使用_aligned_malloc函数即可。

 

实例如下:

#include 

#include 

#include 

 

// Structure tobe used for a list item; the first member is the

// SLIST_ENTRYstructure, and additional members are used fordata.

// Here, thedata is simply a signature for testing purposes.

 

 

typedef struct _PROGRAM_ITEM {

    SLIST_ENTRYItemEntry;

    ULONGSignature;

} PROGRAM_ITEM,*PPROGRAM_ITEM;

 

int main( )

{

    ULONGCount;

    PSLIST_ENTRYpFirstEntry, pListEntry;

    PSLIST_HEADERpListHead;

    PPROGRAM_ITEMpProgramItem;

 

    //Initialize the list header to a MEMORY_ALLOCATION_ALIGNMENTboundary.

    pListHead= (PSLIST_HEADER)_aligned_malloc(sizeof(SLIST_HEADER),

       MEMORY_ALLOCATION_ALIGNMENT);

    if( NULL ==pListHead )

    {

        printf("Memory allocation failed./n");

        return -1;

    }

    InitializeSListHead(pListHead);

 

    // Insert10 items into the list.

    for( Count = 1;Count <= 10; Count += 1 )

    {

        pProgramItem= (PPROGRAM_ITEM)_aligned_malloc(sizeof(PROGRAM_ITEM),

            MEMORY_ALLOCATION_ALIGNMENT);

        if( NULL ==pProgramItem )

        {

            printf("Memory allocation failed./n");

            return -1;

        }

        pProgramItem->Signature= Count;

        pFirstEntry= InterlockedPushEntrySList(pListHead,

                       &(pProgramItem->ItemEntry));

    }

 

    // Remove10 items from the list and display the signature.

    for( Count = 10;Count >= 1; Count -= 1 )

    {

        pListEntry= InterlockedPopEntrySList(pListHead);

 

        if( NULL ==pListEntry )

        {

            printf("List is empty./n");

            return -1;

        }

 

        pProgramItem= (PPROGRAM_ITEM)pListEntry;

        printf("Signature is %d/n",pProgramItem->Signature);

 

    // Thisexample assumes that the SLIST_ENTRY structure isthe

    // firstmember of the structure. If your structure doesnot

    // followthis convention, you must compute the startingaddress

    // of thestructure before calling the free function.

 

        _aligned_free(pListEntry);

    }

 

    // Flushthe list and verify that the items are gone.

    pListEntry= InterlockedFlushSList(pListHead);

    pFirstEntry= InterlockedPopEntrySList(pListHead);

    if (pFirstEntry != NULL)

    {

        printf("Error: List is not empty./n");

        return -1;

    }

 

    _aligned_free(pListHead);

 

    return 1;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值