InterlockedIncrement vs InterlockedIncrementAcquir

2019-06-13 19:08发布

问题:

This is a followup to this question:

I guess I don't understand the Interlocked Acquire / Release APIs. I put together the small program below. As I understand it, g_val_1, g_val_2 and g_val_3 should always be updated in the same order and should end up as all the same value. But they do not (for more than one thread).

What am I missing? Thanks.

#include "windows.h"
#include "stdio.h"

#define _THREADS_    100
#define _TICKS_      1000

int volatile g_threads = 0;
DWORD volatile g_val_1 = 0;
DWORD volatile g_val_2 = 0;
DWORD volatile g_val_3 = 0;

BOOL g_running = TRUE;

DWORD TestThread(PVOID ignore)
{
    while (g_running)
    {
        InterlockedIncrementAcquire(&g_val_1);
        g_val_2++;
        InterlockedIncrementRelease(&g_val_3);
    }
    InterlockedDecrement(&g_threads);
    return(0);
}

int __cdecl main(int argc, char* argv[])
{
    int th, duration;
    int success;
    DWORD ticks;
    duration = _TICKS_;
    g_threads = _THREADS_;
    printf("Max=%d Threads=%d Entries=%d\n", duration, g_threads);
    printf("Creating Threads\n");
    th = g_threads;
    while (th-- > 0)
    {
        CreateThread(NULL,
                0,
                TestThread,
                NULL,
                NORMAL_PRIORITY_CLASS,
                NULL);
    }
    printf("Starting Threads\n");
    ticks = GetTickCount();
    while ((GetTickCount() - ticks) < duration);
    g_running = FALSE;
    while (g_threads > 0);
    ticks = GetTickCount() - ticks;
    success = ((g_val_1 == g_val_2) && (g_val_1 == g_val_2));
    printf("Duration=%d g_val_1=%d g_val_2=%d g_val_3=%d OK=%d\n", ticks, g_val_1, g_val_2, g_val_3, success);
}