Is this code safe?

Just starting out? Need help? Post your questions and find answers here.
User avatar
ostapas
Enthusiast
Enthusiast
Posts: 192
Joined: Thu Feb 18, 2010 11:10 pm

Is this code safe?

Post 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.
auser
Enthusiast
Enthusiast
Posts: 195
Joined: Wed Sep 06, 2006 6:59 am

Re: Is this code safe?

Post 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.
User avatar
ostapas
Enthusiast
Enthusiast
Posts: 192
Joined: Thu Feb 18, 2010 11:10 pm

Re: Is this code safe?

Post 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 :)
Post Reply