Udostępnij za pośrednictwem


_AcquireSpinLock

Microsoft Specific

Used to enter a critical section, effectively ensuring that no other thread is able to execute the code path between the call to _AcquireSpinLock and the call to _ReleaseSpinLock.

void _AcquireSpinLock(
   unsigned __int64 * Lock
)

Parameters

  • [out] Lock
    The lock variable: set to 1 when a lock is acquired.

Remarks

Other threads attempting to execute _AcquireSpinLock block until the thread with the lock calls _ReleaseSpinLock.

This routine is only available as an intrinsic.

Requirements

Intrinsic

Architecture

_AcquireSpinLock

IPF

Header file <intrin.h>

Example

// spinlock.cpp
// compile with: /MT 
// processor: IPF

#include <cstdlib>
#include <cstdio>
#include <process.h>
#include <windows.h>
#include <intrin.h>
 
#pragma intrinsic(_AcquireSpinLock, _ReleaseSpinLock)

// Data to protect.

volatile LONG data = 0;
unsigned __int64 lock = 0;  
void __cdecl SimpleThread(void* pParam);
const int THREAD_COUNT = 6;

int main()
{
    DWORD num;
    HANDLE threads[THREAD_COUNT];
    int args[THREAD_COUNT];
    int i;

    for (i = 0; i < THREAD_COUNT; i+)
    {
        args[i] = i+1;
        threads[i] = 
             reinterpret_cast<HANDLE>(_beginthread(SimpleThread,
                                      0, args + i));
        if (threads[i] == reinterpret_cast<HANDLE>(-1))
        {
            // Error creating threads
            break;
       }
    }
 
    WaitForMultipleObjects(i, threads, true, INFINITE);
}

// Code for the simple thread
void __cdecl SimpleThread(void* pParam)
{
    int thread = *( (int*) pParam);
    int k = 1;

    _AcquireSpinLock(&lock);

    int x1 = data++;
    for (int i = 0; i < 10000; i+)
    {
        // Perform some calculations to create a delay
        k += i;
        k %= 10000;
    }
    int x2 = data++;   
   
    printf_s("%I64d %d %d %d\n", lock, thread, x1, k);
    printf_s("%I64d %d %d %d\n", lock, thread, x2, k);

    _ReleaseSpinLock(&lock);

    if (x2 - x1 != 1)
        printf_s("Error!\n");
}

1 1 0 5001 1 1 1 5001 1 3 2 5001 1 3 3 5001 1 2 4 5001 1 2 5 5001 1 4 6 5001 1 4 7 5001 1 5 8 5001 1 5 9 5001 1 6 10 5001 1 6 11 5001

See Also

Reference

_ReleaseSpinLock

Compiler Intrinsics