The thread needs to communicate with each other in the following two cases:
• When multiple threads access shared resources, the resources are not damaged.
• When one thread needs to notify another or more threads of the completion of a task.
The so-calledAtomic accessWhen a thread accesses a resource, it ensures that all other threads do not access the same resource at the same time.
All functions starting with InterLocked are account number functions. UseAdvantages of mutual lock FunctionsYes: It is much faster than other CriticalSection, Mutex, Event, and Semaphore. Calling an interlock function usually leads to several CPU cycles (usually less than 50) and will not be converted from the user mode to the kernel mode (usually 1000 CPU cycles are required ). View msdn (http://msdn2.microsoft.com/en-us/library/ms686360.aspx)
The first function:
LONG InterlockedExchangeAdd(
PLONG plAddend,
LONG Increment);
A simple example:
# Include "stdafx. h"
# Include <iostream>
# Include <windows. h>
# Include <process. h>
Using namespace std;
# Define THREAD_MAX 2 // no more than 64 kernel objects
Long g_x = 0;
Unsigned _ stdcall ThreadEntity (void * pVoid)
{
// G_x ++; // No security protection
InterlockedExchangeAdd (& g_x, 1); // The interlock function provides security protection.
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;
}
The second function:
UseLONGInterlockedExchange(PLONG plTarget, LONG lValue); Implement loop lock:
// 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 pm