Need help with threading(yes ive done everything else first)

Rockstar

New member
Joined
Mar 6, 2011
Messages
3
Programming Experience
1-3
So ive looked and looked...and looked again...under rocks, pages of google bing and yahoo. msdn, and i cant seem to find the one thing i want to know.

say i want x amount of threads running that count to 8.
x = 4 in this case.

example:
t1=1
t2=2
t3=3
t4=4
t1=5
t2=6
t3=7
t4=8

i cant do t1/t4.start() because each thread will count to 8 on its own.
tried to loop the starting of the thread, however that starts the thread then restarts it when its finished.


ive been stumped on this for months, literally, and im tired of asking and tired of reading because i havent ever found a definitive answer to how this should work.
if i can id prefer to stay away from backgroundworkers as its a personal preference to work with system.threading.thread.

anybody? thanks in advance :)
 
Last edited:
For i = 1 To 4
    Dim t As New Threading.Thread(AddressOf Counter)            
    t.Start()
Next

Sub Counter()
    Static sync As New Object
    Static count As Integer
    Do
        SyncLock sync
            If count < 8 Then
                count += 1
                Debug.WriteLine("count {0} : id {1}", count, Threading.Thread.CurrentThread.ManagedThreadId)
            Else
                Exit Do
            End If
        End SyncLock
    Loop
End Sub
 
The reason that you can't find a solution is because that's a ridiculous thing to have multiple threads do. You would need complex synchronisation to do something completely trivial. Perhaps you could explain what useful scenario you're trying to implement and we can help because what you've actually asked for is no way to learn multithreading.
 
Counting asynchronous is indeed ridiculous. Counting is inherently a synchronous operation, and multi-threading means asynchronous processing. The code example I posted will actually always count in order, and also split work between the assigned threads, but in effect the whole operation is performed synchronous because any thread will wait to enter the SyncLock block.

Here is another example using the new Task Parallel Library in .Net 4 where counting by Parallel.For is done asynchronous, ie the output is an unordered list of the numbers and the threads that handled them. Max number of threads is here simply a property of ParallelOptions.
Dim body As New Action(Of Integer)(Sub(x) Debug.WriteLine("count {0} : id {1}", x, Threading.Thread.CurrentThread.ManagedThreadId))
Dim opt As New Threading.Tasks.ParallelOptions
opt.MaxDegreeOfParallelism = 4
Threading.Tasks.Parallel.For(1, 9, opt, body)

The equivalent in traditional multi-threading programming would be to generate the numbers into a queue and have a batch of threads process it.
 
Back
Top