Hi,
I'm trying to see how works the ThreadingPool :
Dim iNumThread As Integer = 0
Sub Main()
For i = 1 To 5
ThreadPool.QueueUserWorkItem(AddressOf Traitement, i * 2)
Next
Console.ReadLine();
End Sub
Sub Traitement(ByVal Obj As Object)
NumeroterThread()
Console.WriteLine("Le thread {0} d?marre un traitement sur : {1}", _
Thread.CurrentThread.Name, Obj.ToString)
Thread.Sleep(5000)
Console.WriteLine("Le thread {0} termine un traitement sur : {1}", _
Thread.CurrentThread.Name, Obj.ToString)
End Sub
Sub NumeroterThread()
If Thread.CurrentThread.Name = String.Empty Then
Interlocked.Increment(iNumThread)
Thread.CurrentThread.Name = iNumThread.ToString
End If
End Sub
Running this example, i see that the two first threads have always the
same name, ie the same number despite the use of Interlocked.Increment
method. So i ask where is the pb : on my use of this method or with the
TreadPool. Anyway, if i place the if of the NumeroterThread Sub in a
SyncLock block, it works, but from my point of view the
Interlocked.Increment method should do the job ?
Thanks and best regards
Gilles
Mattias Sj?gren - 17 Feb 2005 14:47 GMT
>So i ask where is the pb : on my use of this method or with the
>TreadPool.
Your lack of synchronization is the problem. Consider this
Thread A calls Interlocked.Increment
Thread B calls Interlocked.Increment
Thread A assigns CurrentThread.Name
Thread B assigns CurrentThread.Name
Now they will obviously have the same name.
You could consider doing this though
Thread.CurrentThread.Name = Interlocked.Increment(iNumThread).ToString
Mattias

Signature
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Gilles Lambert - 18 Feb 2005 17:25 GMT