Page 2 of 2

Re: What to use AddMapElement for?

Posted: Thu Oct 31, 2024 11:25 pm
by idle
Bisonte wrote: Thu Oct 31, 2024 10:55 pm
idle wrote: Thu Oct 31, 2024 10:27 pm Also worth mentioning Maps aren't 100% Thread safe.
The current element could potentially change if the map is being accessed across threads.
so if there's any uncertainty use an appropriately scoped mutex or you might end up mixing an elements fields with another

Code: Select all

LockMutex(MapMutex)
If Not FindMapElement(Clients(),key)  
      If AddMapElement(Clients(),key)
           clients()\ID = clientID                      ;these could be corrupted without mutex                  
           clients()\lock = CreateMutex()      
      EndIf 
 EndIf          
UnlockMutex(MapMutex)
so you mean, this one should be Threadsafe without LockMutex ?

Code: Select all

If Not FindMapElement(Clients(), key)  
  *MapElement.myStructure = AddMapElement(Clients(), key)
  If *MapElement
    *MapElement\ID = clientID
    *MapElement\lock = CreateMutex()
  EndIf 
EndIf    
That's definitely safer using a pointer but an async call to FindMapElement could still return the wrong element in the middle of AddMapElement and you probably wouldn't know as it wouldn't cause a crash.
It should be fairly easy to do a test.