Page 1 of 1

Is this code safe?

Posted: Thu Oct 23, 2014 11:20 pm
by ostapas
Good day or night,
I have a situation where I need to add/remove elements to global linked list from multiple threads. For example:

Code: Select all

If Not #PB_Compiler_Thread   
  MessageRequester("", "Run in threadsafe mode", #MB_OK|#MB_ICONERROR)
  End
EndIf

Global NewList Guinea_Pig.s()
Global Mutex = CreateMutex()

Procedure Add_Remove_Element_To_List(Void)
  
  Repeat
    
    Delay(Random(1000))
    LockMutex(Mutex)
    AddElement(Guinea_Pig())
    Guinea_Pig() = Str(Random(9999999))
    FirstElement(Guinea_Pig())
    DeleteElement(Guinea_Pig(), 1)
    UnlockMutex(Mutex)    
    
  ForEver
  
EndProcedure

For i = 1 To 100
  CreateThread(@Add_Remove_Element_To_List(), 0)  
Next

MessageRequester("", "Click OK to finish")
This is working fine. However, theoretically, is it safe to run such kind of code for a long period?(some days). Could this be a reason of mysterious crashes/freezes/IMAs ? Thanks.

Re: Is this code safe?

Posted: Fri Oct 24, 2014 7:31 am
by auser
If you would increase the safety then I would recommend to add some "If". "If AddElement" and "If FirstElement" to make sure your elements are available before you are going to use them. However your list does not consume much memory anyway. You lock, add the first element, switch to the first and only element, delete the first and only element (so flag 1 for DeleteElement does not make much sense currently) and unlock again and again. Every thread starts with 0 elements in the list and ends with 0 elements in the list and the total amount of elements if the threads are done is always 0 even after days.

Re: Is this code safe?

Posted: Fri Oct 24, 2014 8:43 am
by ostapas
Auser, thanks, I will add additional ifs. Actually the list will contain millions of elements, that's why I want to make sure isn't such list raping not reccomended :)