In the previous article, we had a dirty reading problem, but did not give a solution to this article in this article, we mainly explain the interlocked series functions.
Some common interlocked series functions are listed below:
1. Increase or decrease operation
Long__cdeclinterlockedincrement (LONG volatile* Addend);
Long__cdeclinterlockeddecrement (LONG volatile* Addend);
Returns the value of the variable after the increment or decrement operation is performed.
Long__cdec InterlockedExchangeAdd (LONG volatile* Addend, Longvalue);
Returns the value after the operation, (note) A negative number is the minus.
2. Assignment operation
Long__cdeclinterlockedexchange (LONG volatile* Target, Longvalue);
Value is the new value, and the function returns the original value.
In this case, you can just use the InterlockedIncrement () function. Let's make a list of the code below.
<span style= "FONT-SIZE:14PX;" > #include <stdio.h> #include <windows.h> volatile long g_nlogincount; Number of logins unsigned int __stdcall fun (void *ppm); Thread Function const DWORD Thread_num = 50;//start thread number DWORD WINAPI threadfun (void *ppm) {Sleep];//some W Ork should to do//g_nlogincount++; InterlockedIncrement ((Lplong) &g_nlogincount); Sleep (50); return 0; } int main () {printf ("Atomic Operation interlocked series function \ n"); printf ("-by Morewindows (http://blog.csdn.net/MoreWindows)--\n\n"); Repeat 20 times to observe the conflicts that result when multiple threads access the same resource int num= 20; while (num--) {g_nlogincount = 0; int i; HANDLE Handle[thread_num]; for (i = 0; i < thread_num; i++) Handle[i] = CreateThread (null, 0, threadfun, NULL, 0, NULL); WaitForMultipleObjects (Thread_num, handle, TRUE, INFInite); printf ("%d users log results after logging%d\n", Thread_num, G_nlogincount); } return 0; } </span>
Therefore, in the multi-threaded environment, we have to think carefully about these simple statements of variable self-increment, to prevent the data access error caused by multiple threads.
Multi-threaded interview second KILL series 4---A brief analysis of interlocked series functions