Windows編程-- 使用者方式中線程的同步—原子訪問:互鎖的函數家族

來源:互聯網
上載者:User


線程需要在下面兩種情況下互相進行通訊:

•當有多個線程訪問共用資源而不使資源被破壞時。

•當一個線程需要將某個任務已經完成的情況通知另外一個或多個線程時。

 

所謂原子訪問,是指線程在訪問資源時能夠確保所有其他線程都不在同一時間內訪問相同的資源。

以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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.