|
-
Nov 14th, 2002, 08:04 AM
#1
Thread Starter
Lively Member
Variables and Threading
Ok, here is my dilemma. I have a multi-threaded application using threadpooling that spawns multiple threads as needed. Inside my sub-routine I have a variable named strCounter. The problem is, when more than one thread gets called it is sharing the strCounter variable. How can I keep the variable unique to that thread so that it does not get incremented from other threads. I am diming the variable in the main class as Private which does not appear to help.
Here is a example:
Public Class Main
Private strCounter as integer
Sub Timer
While oDataReader.Read()
ThreadPool.QueueUserWorkItem(AddressOf Reboot, oDataReader("Server") & "|" & oDataReader("PKey") & "|" & oDataReader("Notify"))
End While
End Sub
Public Sub Reboot(ByVal State As Object)
Code....
strCounter += 1
End Sub
End Class
-
Nov 14th, 2002, 08:06 AM
#2
Thread Starter
Lively Member
One more thing. I cannot dim the variable in the Reboot sub-routine or it will get reset each time I recall the sub from within the sub.
Public Sub Reboot(ByVal State As Object)
If whatever = whatever then
Call Reboot(value)
End If
strCounter += 1
End Sub
-
Nov 14th, 2002, 08:42 AM
#3
PowerPoster
Check out the System.Threading.Interlocked class. This class locks the resouce that can be accessed from multiple threads and releases the lock when the thread is done with it.
-
Nov 14th, 2002, 10:04 AM
#4
Thread Starter
Lively Member
I actually need to do the opposite:
"The simplest case is if you have a shared variable that you need to update from different threads. To do this, you can use the System.Threading.Interlocked class. For example, to increment or decrement the shared variable called num, you'd write Interlocked.Increment(num) or Interlocked.Decrement(num)."
I need to make the variable unique to that thread and only updatable by that thread. This apparently makes it so that one variable can be updated by multiple threads or am I reading this incorrectly?
-
Nov 14th, 2002, 10:39 AM
#5
PowerPoster
Ok, check of the AllocateNamedDataSlot() Class:
Threads use a local store memory mechanism to store thread-specific data. The common language runtime allocates a multi-slot data store array to each process when it is created. The thread can allocate a data slot in the data store, store and retrieve a data value in the slot, and free the slot for reuse after the thread expires. Data slots are unique per thread. No other thread (not even a child thread) can get that data.
-
Nov 14th, 2002, 11:06 AM
#6
Thread Starter
Lively Member
Took an alternate path to my logic and placed the code in a do while loop and made the variable local to the thread. Appears to be working really well! Thanks again for the help...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|