I have a MultiThreading issue and conceptual question using Visual Basic (but it applies to almost all languages).
I have a function which:
- creates 5 instances of a class which each spawns a thread which calls a function
- The Function sleeps for X milli-seconds
- prints to console
- then terminates the thread
How can I ensure all instances of the class gets a chance to finish before main cuts it off??
Most relevant help through research: How do I pause main() until all other threads have died?
Here is my code:
Imports System
Imports System.Threading
Imports System.Collections.Generic
Module Module1
Private raceTrack As New List(Of RaceCar)
Sub Main()
CreateRace()
'Main() would quit when the 5 car objects are created =[
'How do I make sure Main will not exit until all racecars are done?
End Sub
Sub CreateRace()
For index As Integer = 1 to 5
raceTrack.Add(new RaceCar(index))
Next
End Sub
Public Class RaceCar
Private testThread as Thread = New Thread(AddressOf StartEngine)
Private carId as Integer
Public Sub New(ByVal carNumber as Integer)
me.carId = carNumber
Me.TestThread.Start()
Me.TestThread.Join()
End Sub
Public Sub StartEngine()
Console.WriteLine(String.Format("Car#{0} is going!", Me.carId))
Thread.Sleep(100*Me.carId)
Console.WriteLine(String.Format("Car#{0} is DONE!", Me.carId))
End Sub
End Class
End Module
Apparently your
RaceCarconstructor only returns when the spawned thread finishes, since you are callingJoin.I don’t know if this is intentional (most likely not, because you are creating your
RaceCarinstances in a loop, so you have no parallelism, since the next instance cannot be created until the previous constructor call returns), but definitely your main thread cannot finish until all the child threads have finished.I suggest the following restructuring:
Remove the
Joinfrom the constructor and add a new method in yourRaceCarclass:Now the object creation loop will not block. Add another loop afterwards:
Now your threads will start in the first loop, run their work in parallel and eventually stop on the new “barrier loop”.
Note that the main thread can still do other tasks between the two loops.
(Disclaimer: I’ve never programmed in vb.net, so hopefully what I wrote is not totally wrong.)