JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Synchronizing Threads

When you start multiple threads and need to coordinate their operation in some way—for instance, so that they can share the same resource in memory—you need to synchronize them. As mentioned in the In Depth section of this chapter, you can use events to communicate between threads. You also can use the SyncLock statement or the Join method—see the next two topics in this chapter.

For example, we took a look at all these techniques in the SynchronizeThreads example, discussed in the In Depth section of this chapter. In that example, we created a new class named counter with one data member, Total:

Public Class counter
    Public Total As Integer
End Class

The SynchronizeThreads example used two synchronized threads to increment the Total data member to a value of 200, as you see in Figure 24.11. Here's the code for the main form in that example, Form1.vb:

Public Class Form1
    Inherits System.Windows.Forms.Form
    Dim c As New counter()
    Dim Thread1 As New System.Threading.Thread(AddressOf Counter1)
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Dim Thread2 As New System.Threading.Thread(AddressOf Counter2)

' Windows Form Designer generated code...

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        Thread1.Start()
        Thread2.Start()
        Thread1.Join()
        Thread2.Join()
        TextBox1.Text = c.Total
    End Sub

    Private Sub Counter1()
        Dim LoopIndex As Integer
        For LoopIndex = 1 To 100
            SyncLock c.GetType
                Dim temp = c.Total
                Thread1.Sleep(1)
                c.Total = temp + 1
            End SyncLock
        Next LoopIndex
    End Sub

    Private Sub Counter2()
        Dim LoopIndex As Integer

        For LoopIndex = 1 To 100
            SyncLock c.GetType
                Dim temp = c.Total
                Thread2.Sleep(1)
                c.Total = temp + 1
            End SyncLock
        Next LoopIndex
    End Sub
End Class

For more details on this example, see the discussion in the In Depth section of this chapter, and the next two topics.

Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor