Spinlock with Memory Allocation

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
FunnyGuy9796
Member
Member
Posts: 61
Joined: Tue Sep 13, 2022 9:29 pm
Libera.chat IRC: FunnyGuy9796

Spinlock with Memory Allocation

Post 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.
Octocontrabass
Member
Member
Posts: 5562
Joined: Mon Mar 25, 2013 7:01 pm

Re: Spinlock with Memory Allocation

Post 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.
FunnyGuy9796
Member
Member
Posts: 61
Joined: Tue Sep 13, 2022 9:29 pm
Libera.chat IRC: FunnyGuy9796

Re: Spinlock with Memory Allocation

Post 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 :)
rdos
Member
Member
Posts: 3296
Joined: Wed Oct 01, 2008 1:55 pm

Re: Spinlock with Memory Allocation

Post 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.
Post Reply