Alternative to Windows InterlockedIncrement64 using c++

1k Views Asked by At

I'm using InterlockedIncrement64 in my application for atomic increment to make sure it is thread safe, My code is required to be based only on c runtime library, I decided to use the atomic class I wrote the following 2 methods

#include "stdafx.h"
#include <iostream>
#include <atomic>
#include "time.h"
using namespace std;

void InterLockedIncrement64(int64_t* input)
{
    /*static*/ atomic<int64_t> ato(*input);
    //ato.store(*input);
    ato.fetch_add(1);
    *input = ato.load();
}
void InterlockedIncrement64_(int64_t* input)
{
    atomic<int64_t> *atomicData = reinterpret_cast<atomic<int64_t>*>(input);
    atomicData->fetch_add(1);
}
int _tmain(int argc, _TCHAR* argv[])
{
    int64_t count = 0;
    int64_t count_ = 0;
    while (true)
    {
        clock_t c = clock();
        for (int i = 0; i < 1000001; i++)
        {
            InterlockedIncrement64_(&count_);
        }
        uint32_t time1 = clock() - c;
        c = clock();
        for (int i = 0; i < 1000001; i++)
        {
            InterLockedIncrement64(&count);
        }
        uint32_t time2 = clock() - c;

        cout << "Time 1 = " << time1 << endl;
        cout << "Time 2 = " << time2 << endl;

        char in = cin.get();
        if(in == 'c')
        {
            break;
        }
    }
    system("pause");
    return 0;
}

I think that the first method is fine (I need confirmation for this)!, the second method calculated the same result but not in tested in multi-threading but it is faster, the second one is suspicious for me, I need advice from those who have experience.

0

There are 0 best solutions below