C++ Programmer's Cookbook

{C++ 基础} {C++ 高级} {C#界面,C++核心算法} {设计模式} {C#基础}

C++多线程(四)

多线程同步之WIN API互锁函数 (可以避免使用CriticalSection或Mutex

一 互锁函数

      互锁函数的家族十分的庞大,可以查看msdn(http://msdn2.microsoft.com/en-us/library/ms686360.aspx)以InterLocked开始的函数都是户数函数。使用互锁函数的优点是:他的速度要比其他的CriticalSection,Mutex,Event,Semaphore快很多。

二 简单实例

      使用一些实例说明部分互锁函数的使用:

1) LONG InterlockedExchangeAdd(   PLONG plAddend,LONG Increment);

简单实例,在线程函数中对全局的变量自增,在开始使其为0,在线程都执行完以后输出全局变量的值,如果我们不使用互锁函数,则最后输出的结果,大部分情况是不正确的,比如我们一共有10000个线程的话,则全局变量的值一般是比10000要小;但是如果我们使用互锁函数来实现自增,则就快速的实现了线程安全,最后输出的全局变量一定是10000.

#include <windows.h>
#include 
<process.h>
#include 
<stdio.h>

#define THREAD_MAX 100000

int g_x = 0;

unsigned  __stdcall ThreadEntity(
void * pVoid)
{
    g_x
++;
    
//InterlockedExchangeAdd(reinterpret_cast<long*>(&g_x),1);    
    return 1;        
}

int main()
{     

    HANDLE   hth[THREAD_MAX];
    unsigned  uiThreadID[THREAD_MAX];

    printf(
"start create children threadings:\n");
    
for(int i = 0; i < THREAD_MAX; ++i)
    
{
        hth[i] 
= (HANDLE)_beginthreadex( NULL,         // security
            0,            // stack size
            ThreadEntity,
            (
void*)&i,           // arg list
            0,  
            
&uiThreadID[i] );

        
if ( hth[i]== 0 )
            printf(
"Failed to create thread 1\n");        
    }


    WaitForMultipleObjects( THREAD_MAX, hth,
true,10000);   

    
for(int i = 0; i<THREAD_MAX; ++i)
        CloseHandle( hth[i] );
    
    printf(
"last: g_x is %d\n",g_x);

    printf(
"Primary thread terminating.\n");
}

在上面的代码中使用了 //InterlockedExchangeAdd(reinterpret_cast<long*>(&g_x),1); 来实现g_x的线程安全的自增。  

2)使用LONG InterlockedExchange(PLONG plTarget,LONG lValue);实现循环锁:

// Global variable indicating whether a shared resource is in use or not
BOOL g_fResourceInUse = FALSE;


void Func1() 
{
   
//Wait to access the resource.
   while(InterlockedExchange(&g_fResourceInUse, TRUE) == TRUE)
      Sleep(
0);

   
//Access the resource.

   

   
//We no longer need to access the resource.
   InterlockedExchange(&g_fResourceInUse, FALSE);
}

 
3)太多了,不举了,以后用到了再放到这里把。

三 互锁函数列表

一般的互锁函数:
Interlocked function Description
InterlockedAdd Performs an atomic addition operation on the specified LONG values.
InterlockedAdd64 Performs an atomic addition operation on the specified LONGLONG values.
InterlockedAddAcquire Performs an atomic addition operation on the specified LONG values. The operation is performed with acquire memory access semantics.
InterlockedAddAcquire64 Performs an atomic addition operation on the specified LONGLONG values. The operation is performed with acquire memory access semantics.
InterlockedAddRelease Performs an atomic addition operation on the specified LONG values. The operation is performed with release memory access semantics.
InterlockedAddRelease64 Performs an atomic addition operation on the specified LONGLONG values. The operation is performed with release memory access semantics.
InterlockedAnd Performs an atomic AND operation on the specified LONG values.
InterlockedAndAcquire Performs an atomic AND operation on the specified LONG values. The operation is performed with acquire memory access semantics.
InterlockedAndRelease Performs an atomic AND operation on the specified LONG values. The operation is performed with release memory access semantics.
InterlockedAnd8 Performs an atomic AND operation on the specified char values.
InterlockedAnd8Acquire Performs an atomic AND operation on the specified char values. The operation is performed with acquire memory access semantics.
InterlockedAnd8Release Performs an atomic AND operation on the specified char values. The operation is performed with release memory access semantics.
InterlockedAnd16 Performs an atomic AND operation on the specified SHORT values.
InterlockedAnd16Acquire Performs an atomic AND operation on the specified SHORT values. The operation is performed with acquire memory access semantics.
InterlockedAnd16Release Performs an atomic AND operation on the specified SHORT values. The operation is performed with release memory access semantics.
InterlockedAnd64 Performs an atomic AND operation on the specified LONGLONG values.
InterlockedAnd64Acquire Performs an atomic AND operation on the specified LONGLONG values. The operation is performed with acquire memory access semantics.
InterlockedAnd64Release Performs an atomic AND operation on the specified LONGLONG values. The operation is performed with release memory access semantics.
InterlockedBitTestAndReset Tests the specified bit of the specified LONG value and sets it to 0.
InterlockedBitTestAndReset64 Tests the specified bit of the specified LONG64 value and sets it to 0.
InterlockedBitTestAndSet Tests the specified bit of the specified LONG value and sets it to 1.
InterlockedBitTestAndSet64 Tests the specified bit of the specified LONG64 value and sets it to 1.
InterlockedCompare64Exchange128 Performs an atomic compare-and-exchange operation on the specified values. The function compares the specified 64-bit values and exchanges with the specified 128-bit value based on the outcome of the comparison.
InterlockedCompare64ExchangeAcquire128 Performs an atomic compare-and-exchange operation on the specified values. The function compares the specified 64-bit values and exchanges with the specified 128-bit value based on the outcome of the comparison. The operation is performed with acquire memory access semantics.
InterlockedCompare64ExchangeRelease128 Performs an atomic compare-and-exchange operation on the specified values. The function compares the specified 64-bit values and exchanges with the specified 128-bit value based on the outcome of the comparison. The operation is performed with release memory access semantics.
InterlockedCompareExchange Performs an atomic compare-and-exchange operation on the specified values. The function compares two specified 32-bit values and exchanges with another 32-bit value based on the outcome of the comparison.
InterlockedCompareExchange64 Performs an atomic compare-and-exchange operation on the specified values. The function compares two specified 64-bit values and exchanges with another 64-bit value based on the outcome of the comparison.
InterlockedCompareExchangeAcquire Performs an atomic compare-and-exchange operation on the specified values. The function compares two specified 32-bit values and exchanges with another 32-bit value based on the outcome of the comparison. The operation is performed with acquire memory access semantics.
InterlockedCompareExchangeAcquire64 Performs an atomic compare-and-exchange operation on the specified values. The function compares two specified 64-bit values and exchanges with another 64-bit value based on the outcome of the comparison. The exchange is performed with acquire memory access semantics.
InterlockedCompareExchangePointer Performs an atomic compare-and-exchange operation on the specified pointer values. The function compares two specified pointer values and exchanges with another pointer value based on the outcome of the comparison.
InterlockedCompareExchangePointerAcquire Performs an atomic compare-and-exchange operation on the specified pointer values. The function compares two specified pointer values and exchanges with another pointer value based on the outcome of the comparison. The operation is performed with acquire memory access semantics.
InterlockedCompareExchangePointerRelease Performs an atomic compare-and-exchange operation on the specified pointer values. The function compares two specified pointer values and exchanges with another pointer value based on the outcome of the comparison. The operation is performed with release memory access semantics.
InterlockedCompareExchangeRelease Performs an atomic compare-and-exchange operation on the specified values. The function compares two specified 32-bit values and exchanges with another 32-bit value based on the outcome of the comparison. The exchange is performed with release memory access semantics.
InterlockedCompareExchangeRelease64 Performs an atomic compare-and-exchange operation on the specified values. The function compares two specified 64-bit values and exchanges with another 64-bit value based on the outcome of the comparison. The exchange is performed with release memory access semantics.
InterlockedDecrement Decrements (decreases by one) the value of the specified 32-bit variable as an atomic operation.
InterlockedDecrement64 Decrements (decreases by one) the value of the specified 64-bit variable as an atomic operation.
InterlockedDecrementAcquire Decrements (decreases by one) the value of the specified 32-bit variable as an atomic operation. The operation is performed with acquire memory access semantics.
InterlockedDecrementAcquire64 Decrements (decreases by one) the value of the specified 64-bit variable as an atomic operation. The operation is performed with acquire memory access semantics.
InterlockedDecrementRelease Decrements (decreases by one) the value of the specified 32-bit variable as an atomic operation. The operation is performed with release memory access semantics.
InterlockedDecrementRelease64 Decrements (decreases by one) the value of the specified 64-bit variable as an atomic operation. The operation is performed with release memory access semantics.
InterlockedExchange Sets a 32-bit variable to the specified value as an atomic operation.
InterlockedExchange64 Sets a 64-bit variable to the specified value as an atomic operation.
InterlockedExchangeAcquire Sets a 32-bit variable to the specified value as an atomic operation. The operation is performed with acquire memory access semantics.
InterlockedExchangeAcquire64 Sets a 32-bit variable to the specified value as an atomic operation. The operation is performed with acquire memory access semantics.
InterlockedExchangeAdd Performs an atomic addition of two 32-bit values.
InterlockedExchangeAdd64 Performs an atomic addition of two 64-bit values.
InterlockedExchangeAddAcquire Performs an atomic addition of two 32-bit values. The operation is performed with acquire memory access semantics.
InterlockedExchangeAddAcquire64 Performs an atomic addition of two 64-bit values. The operation is performed with acquire memory access semantics.
InterlockedExchangeAddRelease Performs an atomic addition of two 32-bit values. The operation is performed with release memory access semantics.
InterlockedExchangeAddRelease64 Performs an atomic addition of two 64-bit values. The operation is performed with release memory access semantics.
InterlockedExchangePointer Atomically exchanges a pair of pointer values.
InterlockedExchangePointerAcquire Atomically exchanges a pair of pointer values. The operation is performed with acquire memory access semantics.
InterlockedIncrement Increments (increases by one) the value of the specified 32-bit variable as an atomic operation.
InterlockedIncrement64 Increments (increases by one) the value of the specified 64-bit variable as an atomic operation.
InterlockedIncrementAcquire Increments (increases by one) the value of the specified 32-bit variable as an atomic operation. The operation is performed using acquire memory access semantics.
InterlockedIncrementAcquire64 Increments (increases by one) the value of the specified 64-bit variable as an atomic operation. The operation is performed using acquire memory access semantics.
InterlockedIncrementRelease Increments (increases by one) the value of the specified 32-bit variable as an atomic operation. The operation is performed using release memory access semantics.
InterlockedIncrementRelease64 Increments (increases by one) the value of the specified 64-bit variable as an atomic operation. The operation is performed using release memory access semantics.
InterlockedOr Performs an atomic OR operation on the specified LONG values.
InterlockedOrAcquire Performs an atomic OR operation on the specified LONG values. The operation is performed with acquire memory access semantics.
InterlockedOrRelease Performs an atomic OR operation on the specified LONG values. The operation is performed with release memory access semantics.
InterlockedOr8 Performs an atomic OR operation on the specified char values.
InterlockedOr8Acquire Performs an atomic OR operation on the specified char values. The operation is performed with acquire memory access semantics.
InterlockedOr8Release Performs an atomic OR operation on the specified char values. The operation is performed with release memory access semantics.
InterlockedOr16 Performs an atomic OR operation on the specified SHORT values.
InterlockedOr16Acquire Performs an atomic OR operation on the specified SHORT values. The operation is performed with acquire memory access semantics.
InterlockedOr16Release Performs an atomic OR operation on the specified SHORT values. The operation is performed with release memory access semantics.
InterlockedOr64 Performs an atomic OR operation on the specified LONGLONG values.
InterlockedOr64Acquire Performs an atomic OR operation on the specified LONGLONG values. The operation is performed with acquire memory access semantics.
InterlockedOr64Release Performs an atomic OR operation on the specified LONGLONG values. The operation is performed with release memory access semantics.
InterlockedXor Performs an atomic XOR operation on the specified LONG values.
InterlockedXorAcquire Performs an atomic XOR operation on the specified LONG values. The operation is performed with acquire memory access semantics.
InterlockedXorRelease Performs an atomic XOR operation on the specified LONG values. The operation is performed with release memory access semantics.
InterlockedXor8 Performs an atomic XOR operation on the specified char values.
InterlockedXor8Acquire Performs an atomic XOR operation on the specified char values. The operation is performed with acquire memory access semantics.
InterlockedXor8Release Performs an atomic XOR operation on the specified char values. The operation is performed with release memory access semantics.
InterlockedXor16 Performs an atomic XOR operation on the specified SHORT values.
InterlockedXor16Acquire Performs an atomic XOR operation on the specified SHORT values. The operation is performed with acquire memory access semantics.
InterlockedXor16Release Performs an atomic XOR operation on the specified SHORT values. The operation is performed with release memory access semantics.
InterlockedXor64 Performs an atomic XOR operation on the specified LONGLONG values.
InterlockedXor64Acquire Performs an atomic XOR operation on the specified LONGLONG values. The operation is performed with acquire memory access semantics.
InterlockedXor64Release Performs an atomic XOR operation on the specified LONGLONG values. The operation is performed with release memory access semantics.

链表的互锁函数:
Singly-linked list function Description
InitializeSListHead Initializes the head of a singly linked list.
InterlockedFlushSList Flushes the entire list of items in a singly linked list.
InterlockedPopEntrySList Removes an item from the front of a singly linked list.
InterlockedPushEntrySList Inserts an item at the front of a singly linked list.
QueryDepthSList Retrieves the number of entries in the specified singly linked list.
RtlFirstEntrySList Retrieves the first entry in a singly linked list.
RtlInitializeSListHead Initializes the head of a singly linked list. Applications should call InitializeSListHead instead.
RtlInterlockedFlushSList Flushes the entire list of items in a singly linked list. Applications should call InterlockedFlushSList instead.
RtlInterlockedPopEntrySList Removes an item from the front of a singly linked list. Applications should call InterlockedPopEntrySList instead.
RtlInterlockedPushEntrySList Inserts an item at the front of a singly linked list. Applications should call InterlockedPushEntrySList instead.
RtlQueryDepthSList Retrieves the number of entries in the specified singly linked list. Applications should call QueryDepthSList instead.

posted on 2007-07-26 22:29 梦在天涯 阅读(6891) 评论(9)  编辑 收藏 引用 所属分类: CPlusPlus

评论

# re: C++多线程(四) 2007-07-27 09:30 若弱

第一个例子的结果在默认编译模式下,用InterlockedAdd和++操作结果是完全一样的,根本不会出现线程安全的问题  回复  更多评论   

# re: C++多线程(四) 2007-07-27 14:17 dfl

++操作可能是atomic的

不过如果把print语句放到thread里面就能体现出帖子的要表达的意思了  回复  更多评论   

# re: C++多线程(四) 2007-07-27 17:40 梦在天涯

结果一样吗,我使用的vs2005,结果是不一样啊
,最少我敢说有时是不一样的啊,但可能有写时候可能正好相同,这个取决与系统不同的线程中断,这个不由我们控制。

如果看不到结果,你可以把线程数在加大。

++并不是atomic的,是有2条语句的。  回复  更多评论   

# re: C++多线程(四) 2007-09-26 16:37 GINA

reinterpret_cast<long*>(&g_x)
这个参数不太明白。。希望解释下。谢谢 thank you  回复  更多评论   

# re: C++多线程(四) 2007-09-26 17:06 梦在天涯

reinterpret_cast<long*>(&g_x),是就取地址,然后转化为指向long的指针。  回复  更多评论   

# re: C++多线程(四) 2008-01-21 21:07 小不点

这不就是原子操作吗?好象只能用于操作单条语句,要是执行多条语句是不是就不能用了呢?  回复  更多评论   

# re: C++多线程(四) 2008-06-23 10:15 pgmsoul

reinterpret_cast<long*>(&g_x)
写成(long*)&g_x就完了,说真的,我很BS标准C++的写法,一看就让人觉的高深莫测.  回复  更多评论   

# re: C++多线程(四) 2009-06-10 11:12 aniki

这个例子在我的机器上的执行结果有点怪,偶尔会出现小于THREAD_MAX的值,已经使用InterlockedExchangeAdd(reinterpret_cast<long*>(&g_x),1); 了,不只为什么  回复  更多评论   

# re: C++多线程(四) 2010-09-15 17:34 liziyun537

@aniki
我也是这种情况  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


公告

EMail:itech001#126.com

导航

统计

  • 随笔 - 461
  • 文章 - 4
  • 评论 - 746
  • 引用 - 0

常用链接

随笔分类

随笔档案

收藏夹

Blogs

c#(csharp)

C++(cpp)

Enlish

Forums(bbs)

My self

Often go

Useful Webs

Xml/Uml/html

搜索

  •  

积分与排名

  • 积分 - 1796890
  • 排名 - 5

最新评论

阅读排行榜