Windows编程-- 用户方式中线程的同步原子访问:互锁的函数家族


线程需要在下面两种情况下互相进行通信:

•当有多个线程访问共享资源而不使资源被破坏时。

•当一个线程需要将某个任务已经完成的情况通知另外一个或多个线程时。

 

所谓原子访问,是指线程在访问资源时能够确保所有其他线程都不在同一时间内访问相同的资源

以InterLocked开始的函数都是户数函数。使用互锁函数的优点是:他的速度要比其他的CriticalSection,Mutex,Event,Semaphore快很多。调用一个互锁函数通常会导致执行几个CPU周期(通常小于50),并且不会从用户方式转换为内核方式(通常这需要执行1000个CPU周期)。可以查看msdn(http://msdn2.microsoft.com/en-us/library/ms686360.aspx)

第一个函数:

 

LONG InterlockedExchangeAdd(
PLONG plAddend,
LONG Increment);

一个简单的例子:

#include "stdafx.h"
#include
<iostream>
#include
<windows.h>
#include
<process.h>

using namespace std;

#define THREAD_MAX 2 //不能超过64个内核对象

long g_x = 0;

unsigned __stdcall ThreadEntity(
void * pVoid)
{
//g_x++; //没有安全保护
InterlockedExchangeAdd(&g_x,1); //互锁函数 有安全保护。
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hth[THREAD_MAX];
unsigned uiThreadID[THREAD_MAX];


cout
<< "start create children threadings:"<< endl;
for (inti=0; i<THREAD_MAX; ++i)
{
hth[i]
= (HANDLE)_beginthreadex(NULL, // security
0, // stacksize
ThreadEntity,
(
void*)&i, // arg list
0,
&uiThreadID[i]);

if (hth[i] == 0)
{
cout
<< "Failed to create thread"<< endl;
}
}

WaitForMultipleObjects( THREAD_MAX, hth,
true,100000);

for (inti=0; i<THREAD_MAX; ++i)
{
CloseHandle(hth[i]);
}

cout
<< "last: g_x is " << g_x << endl;
cout
<< "Primary thread terminating." << endl;

system(
"pause");
return 0;
}

第二个函数:

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

// Global variableindicating 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);
}

 FangSH 15:19 2011-1-5

原文地址:https://www.cnblogs.com/fangshenghui/p/1926391.html