RSS .92| RSS 2.0| ATOM 0.3
  • Home
  • About
  •  

    How to Increment/Decrement A Variable In A Thread Safe Manner

    December 31st, 2008

    Sometimes it will be necessary to increment or decrement a variable in a atomic manner so that no other thread can affect it while being incremented/decremented. The complex mutexes and critical sections can do the trick. Still, there is a single line API which does the same and it is

    LONG InterlockedIncrement(LONG volatile* Addend)

    (InterlockedDecrement for decrementing the value).

    For example,

    LONG myNo = 10;
    LONG returnValue = InterlockedIncrement(&myNo);

    will make

    myNO = 11 and returnValue = 11.


    How To Get The Time Elapsed Since The System Was Started

    December 30th, 2008

    The function GetTickCount() (defined in WinBase.h) returns the no. of milliseconds elapsed since the computer was started.

    The returned value is DWORD. So the above call may malfunction if the system has been up continuously for 49.7 days (as DWORD is only 32 bit). You can use the function GetTickCount64(), which returns ULONGLONG,  to overcome this problem.


    How To Get the Processor Speed

    December 19th, 2008

    The processor speed in MHz can be read directly from the registry location HARDWARE\DESCRIPTION\System\CentralProcessor. The following sample code illustrates this.

    DWORD GetProcessorSpeed()
    {
       HKEY hKey;
       // Read the speed from registry
       const long error = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                          "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
                          0,
                          KEY_READ,
                          &hKey);
    
       DWORD dwMHz = 0;
       DWORD BufSize = MAX_PATH;
       if (ERROR_SUCCESS == error)
       {
          RegQueryValueEx(hKey, "~MHz", 0, 0, (LPBYTE)&dwMHz, &BufSize);
       }
       return dwMHz;
    }