Slim Read Write Locking
Posted: Fri Jul 31, 2015 5:03 am
Been slammed recently, so I haven't been able to contribute as much as I would like. Lately I needed a way to serve data to multiple connections concurrently. I created a structured map. and used the Mutex library, but was concerned about the overhead involved using LockMutex when just reading the map. Then I found Slim Reader Writer Lock library:
https://msdn.microsoft.com/en-us/librar ... s.85).aspx
The above code demonstrates that the threads to not collide when using the AcquireSRWLockExclusive() command, and writing to the console. When just reading data, you would use the AcquireSRWLockShared() command.
It was strange, but I could not get TryAcquireSRWLockExclusive to run without it bombing out with an error. Maybe someone else can figure it out.
kernel32.lib can be downloaded with the Microsoft SDK, or I can upload to my website, if needed.
https://msdn.microsoft.com/en-us/librar ... s.85).aspx
Code: Select all
EnableExplicit
Global *globalPointer = AllocateMemory(SizeOf(Integer))
Global sharedInteger.i = 0
Define loopIndex.i
Import "D:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x64\kernel32.lib"
InitializeSRWLock(*globalPointer)
TryAcquireSRWLockShared(*globalPointer)
AcquireSRWLockShared(*globalPointer)
ReleaseSRWLockShared(*globalPointer)
TryAcquireSRWLockExclusive(*globalPointer)
AcquireSRWLockExclusive(*globalPointer)
ReleaseSRWLockExclusive(*globalPointer)
EndImport
InitializeSRWLock(*globalPointer)
OpenConsole()
Procedure incrementInteger(sessionNumber.i)
Protected threadIndex.i
For threadIndex=1 To 10000
AcquireSRWLockExclusive(*globalPointer)
sharedInteger + 1
PrintN("Session = " + Str(sessionNumber) + ", sharedInteger = " + Str(sharedInteger))
ReleaseSRWLockExclusive(*globalPointer)
Delay(10)
Next
PrintN("Session = " + Str(sessionNumber) + " complete")
EndProcedure
For loopIndex=0 To 9
CreateThread(@incrementInteger(), loopIndex)
Next
Delay(10000)
PrintN("Should be done now.")
Input()
CloseConsole()
; IDE Options = PureBasic 5.24 LTS (Windows - x64)
; ExecutableFormat = Console
; CursorPosition = 28
; EnableThread
; Executable = slim_read_write_lock01.exe
; DisableDebugger
; CurrentDirectory = D:\dev\PureBasic\testing\
; CompileSourceDirectoryIt was strange, but I could not get TryAcquireSRWLockExclusive to run without it bombing out with an error. Maybe someone else can figure it out.
kernel32.lib can be downloaded with the Microsoft SDK, or I can upload to my website, if needed.