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.
Quick question about static variables.
- NicTheQuick
- Addict
- Posts: 1523
- Joined: Sun Jun 22, 2003 7:43 pm
- Location: Germany, Saarbrücken
- Contact:
Re: Quick question about static variables.
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.
The english grammar is freeware, you can use it freely - But it's not Open Source, i.e. you can not change it or publish it in altered way.
Re: Quick question about static variables.
It's just as you wrote it.
But it is better to create a structure for the thread and pass it as a parameter.
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)
My Projects ThreadToGUI / OOP-BaseClass / EventDesigner V3
PB v3.30 / v5.75 - OS Mac Mini OSX 10.xx - VM Window Pro / Linux Ubuntu
Downloads on my Webspace / OneDrive
PB v3.30 / v5.75 - OS Mac Mini OSX 10.xx - VM Window Pro / Linux Ubuntu
Downloads on my Webspace / OneDrive
Re: Quick question about static variables.
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.
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.