Page 1 of 1

Spinlock with Memory Allocation

Posted: Thu Jan 12, 2023 6:19 pm
by FunnyGuy9796
I was wondering how a spinlock would come into play in terms of locking or unlocking memory data structures. I read the spinlock article and kind of understand how it works. Although, I am curious as to how it does not lock all memory and only target a certain memory address.

Code: Select all

acquireLock:
    lock bts [lock],0
    jc .spin_with_pause
    ret
 
.spin_with_pause:
    pause
    test dword [lock],1
    jnz .spin_with_pause
    jmp acquireLock
 
releaseLock:
    mov dword [lock],0
    ret
How does this code know what memory data structure to lock? Please excuse my ignorance.

Re: Spinlock with Memory Allocation

Posted: Thu Jan 12, 2023 8:03 pm
by Octocontrabass
FunnyGuy9796 wrote:I read the spinlock article
The example C code in that article is very old. Perhaps it's time for me to update it...
FunnyGuy9796 wrote:How does this code know what memory data structure to lock?
It doesn't. You need a separate lock variable for each structure you want to lock. The example code always uses the same lock variable, so it can only lock one thing.

Re: Spinlock with Memory Allocation

Posted: Thu Jan 12, 2023 8:37 pm
by FunnyGuy9796
Thank you! I had realized how to change the lock variable shortly after posting and I am now kicking myself for not realizing it was a simple variable before :)

Re: Spinlock with Memory Allocation

Posted: Fri Jan 13, 2023 7:56 am
by rdos
Spinlocks are only required when some data is shared between IRQs and mainline code. Spinlocks should not be used as a general lock. For this, it's better to implement semaphores / critical sections that never will waste CPU cycles by other CPUs spinning to get the lock. Instead, ordinary locks should block the thread until the lock becomes available.