Results 1 to 5 of 5

Thread: Theoretical question about subroutines

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    May 2009
    Posts
    459

    Theoretical question about subroutines

    If I call a single subrutine at the same time from two threads (i.e. from the main thread and a BackGroundWorker) I have an error or the same subroutine can be called at the same time from more callers?

    Or best work is to copy / past the same code in different subroutines so that each caller calls its own (identical) subroutine?

    Hoping the question is understandable...
    Last edited by phil2000; Sep 25th, 2016 at 08:38 AM.

  2. #2
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,764

    Re: Theoretical question about subroutines

    As long as the Sub is only manipulating variables that have a block scope, or if the variables have a wider scope e.g. procedure and are protected you should be fine. Here is an example where one sub is called from two different threads, you'll need a button and two labels.

    Code:
    Public Class Form1
    
        Dim aThread As Threading.Thread
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            aThread = New Threading.Thread(AddressOf MainThread)
            aThread.IsBackground = True
            aThread.Start()
        End Sub
    
        Private Sub MainThread()
            Dim tsk1 As Task
            Dim tsk2 As Task
            Dim stpw As Stopwatch = Stopwatch.StartNew
            tsk1 = Task.Run(Sub()
                                DoCount(2000, Label1)
                            End Sub)
    
            tsk2 = Task.Run(Sub()
                                DoCount(5000, Label2)
                            End Sub)
            tsk1.Wait()
            tsk2.Wait()
            stpw.Stop()
            Debug.WriteLine(stpw.Elapsed)
        End Sub
    
        Private Sub DoCount(countTo As Integer, dispTo As Label)
            For x As Integer = 1 To countTo
                Dim i As Integer = x 'gets rid of warning about iteration variable
                dispTo.Invoke(Sub()
                                  dispTo.Text = i.ToString
                                  dispTo.Refresh()
                              End Sub)
            Next
        End Sub
    End Class
    Here is another example that shows procedural scope and A protection mechanism.

    Code:
    Public Class Form1
    
        Dim aThread As Threading.Thread
        Dim aList As New List(Of Integer)
        Dim aListLock As New Object
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            aList.Clear()
            aThread = New Threading.Thread(AddressOf MainThread)
            aThread.IsBackground = True
            aThread.Start()
        End Sub
    
        Private Sub MainThread()
            Dim tsk1 As Task
            Dim tsk2 As Task
            Dim stpw As Stopwatch = Stopwatch.StartNew
            tsk1 = New Task(Sub()
                                FillList(2000)
                            End Sub)
    
            tsk2 = New Task(Sub()
                                FillList(5000)
                            End Sub)
            tsk1.Start()
            tsk2.Start()
            tsk1.Wait()
            tsk2.Wait()
            stpw.Stop()
    
            Debug.WriteLine(stpw.Elapsed)
    
            'determine if both threads were running at the same time
            'look at aList indexes reported here
            Dim firstChg As Integer = -1
            Dim prev As Integer = -1
            For z As Integer = 0 To aList.Count - 1
                If aList(z) < prev Then
                    If firstChg < 0 Then firstChg = z
                    Debug.WriteLine("Index {0}", z)
                End If
                prev = aList(z)
            Next
            If firstChg >= 0 Then
                Debug.WriteLine("*Index {0}", firstChg)
            End If
            Stop 'look at aList values at reported indicies
        End Sub
    
        Private Sub FillList(countTo As Integer)
            Threading.Thread.Sleep(0)
            For x As Integer = 1 To countTo
                Threading.Monitor.Enter(aListLock)
                aList.Add(x)
                Threading.Monitor.Exit(aListLock)
                For i As Integer = 1 To 100
                    Dim z As Integer = i + i
                Next
            Next
        End Sub
    End Class
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,347

    Re: Theoretical question about subroutines

    I haven't read dbasnett's reply and don't doubt that it contains valuable information, but the short answer is that there is no inherent issue calling the same method on multiple threads simultaneously. You should absolutely not duplicate code. There will only be an issue if both threads are manipulating the same data and interfere with each other, e.g. if one thread sets a variable and then later tries to use that variable but another thread has set it to a different value then there might be issues. You need to consider every situation on its own merits and structure your code such that situations like I mentioned earlier don't arise.

  4. #4
    PowerPoster SJWhiteley's Avatar
    Join Date
    Feb 2009
    Location
    South of the Mason-Dixon Line
    Posts
    2,256

    Re: Theoretical question about subroutines

    Quote Originally Posted by phil2000 View Post
    If I call a single subrutine at the same time from two threads ...
    Is there a specific situation you have in mind? it might help to add some context to your question, if DB and JMC don't cover something.
    "Ok, my response to that is pending a Google search" - Bucky Katt.
    "There are two types of people in the world: Those who can extrapolate from incomplete data sets." - Unk.
    "Before you can 'think outside the box' you need to understand where the box is."

  5. #5
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,043

    Re: Theoretical question about subroutines

    I think it was all covered fairly well. The one point I would emphasize is that scope is key. Local variables (those declared in the sub) will be local to the thread. That means that two threads running the same sub will each have their own local variable. If the variable isn't local scope, then it all comes down to context switching, and that can be incredibly subtle, because the threads could switch at all kinds of interesting points, but won't be guaranteed to switch at any point, so the code could do different things at different times, which can be a maddeningly difficult problem to diagnose.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width