Page 1 of 1

Quick question about static variables.

Posted: Fri May 31, 2024 9:55 am
by mikejs
Quick question - if I have a variable defined as static, it appears that it is similar to a global variable, in that it has the same value in all threads.

Is there a way to declare a variable that is like static (local to the procedure), but has a separate value per-thread?

Declaring it threaded is one way, but that is then no longer local to the procedure.

Re: Quick question about static variables.

Posted: Fri May 31, 2024 10:54 am
by NicTheQuick
Unfortunately there is no native way to do that. I usually use Threaded variables for that and give them the procedure name as a prefix. It's basically my own convention to solve that specific problem.

Re: Quick question about static variables.

Posted: Fri May 31, 2024 11:06 am
by mk-soft
It's just as you wrote it.
But it is better to create a structure for the thread and pass it as a parameter.

Code: Select all

;-TOP

Structure udtThreadData
  ; Header
  ThreadID.i
  Exit.i
  ; Data
  Cnt.i
  sParam.s
  sResult.s
EndStructure


Procedure thMyThread(*Data.udtThreadData)
  
  With *Data
    \Cnt + 1
    \sResult = \sParam + " World! Count = " + \Cnt
    Delay(1000)
  EndWith
  
EndProcedure


Global *thData.udtThreadData
*thData = AllocateStructure(udtThreadData)

*thData\sParam = "Hello"

*thData\ThreadID = CreateThread(@thMyThread(), *thData)
If WaitThread(*thData\ThreadID, 5000) = 0
  Debug "Thread Blocked > Kill Thread"
  KillThread(*thData\ThreadID)
Else
  Debug "Thread Result = " + *thData\sResult
EndIf

*thData\ThreadID = CreateThread(@thMyThread(), *thData)
If WaitThread(*thData\ThreadID, 5000) = 0
  Debug "Thread Blocked > Kill Thread"
  KillThread(*thData\ThreadID)
Else
  Debug "Thread Result = " + *thData\sResult
EndIf

FreeStructure(*thData)

Re: Quick question about static variables.

Posted: Fri May 31, 2024 11:30 am
by mikejs
This isn't data for the threaded app itself. It's with regard to a proc in a library that might be used by threaded or unthreaded apps, and which currently has a variable declared as static. My thinking is that this is not threadsafe, and so it needs to do it some other way.

Nic's answer seems to be the best option here - just make it a threaded variable, and give it a more explicit name.

Thanks both - this confirms I haven't missed something in the native options.