What to use AddMapElement for?

Everything else that doesn't fall into one of the other PB categories.
User avatar
idle
Always Here
Always Here
Posts: 5896
Joined: Fri Sep 21, 2007 5:52 am
Location: New Zealand

Re: What to use AddMapElement for?

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