0

我正在尝试将一些多线程应用到我的代码中,因此我试图练习一些简单的任务。在下面的简单代码中,我希望每个线程都取一个计数器(m)的值,然后增加它的值,然后使用之前取的值做一些事情,并将它的结果复制到一个列表(listL)中。不幸的是,我不能阻止线程两次采用相同的值...这可能很简单,但我找不到合适的解决方案...提前谢谢..

马里奥

imports System.Threading

Module Module1
    Public m As UShort = 0
    Dim listL As New List(Of Integer)

Sub Main()
    Dim t1 As New Thread(AddressOf TestMultiThreading)
    Dim t2 As New Thread(AddressOf TestMultiThreading)

    t1.Start("a")
    t2.Start("b")

    t1.Join()
    t2.Join()

    For m As Integer = 0 To listL.Count - 1
        For n As Integer = m + 1 To listL.Count - 1
            If listL(n) = listL(m) Then Debug.Print("same {0} {1}", n, m)
        Next n
    Next m

    listL.Clear()

End Sub

Public Sub TestMultiThreading(ByVal X As Char)
    Dim lobj1 As New Object
    Dim p As Integer

    Do While m < 100
        SyncLock lobj1
            p = m
            m += 1
        End SyncLock
        ' various calculations ...
        ' eventually
        listL.Add(m)
    Loop

    lobj1 = Nothing

    Debug.WriteLine("end " & X)

End Sub

End Module
4

1 回答 1

0

我创建了这个测试。看看区别,特别是锁对象是如何在循环之外的,并且值 p 被添加到列表中,而不是 m。

Module Module1
Public m As Integer = 0
Dim listL As New List(Of String)

Sub Main()
    Dim t1 As New Threading.Thread(AddressOf TestMultiThreading)
    Dim t2 As New Threading.Thread(AddressOf TestMultiThreading)

    t1.Start("a")
    t2.Start("b")
    Threading.Thread.Sleep(0)
    t1.Join()
    t2.Join()

    For xm As Integer = 0 To listL.Count - 1
        Debug.WriteLine(listL(xm))
        For n As Integer = xm + 1 To listL.Count - 1
            If listL(n) = listL(xm) Then
                Debug.Print("same {0} {1}", n, xm)
            End If
        Next n
    Next xm

    listL.Clear()
    Stop
End Sub

Dim lobj1 As New Object

Public Sub TestMultiThreading(ByVal X As Object)

    Dim p As Integer
    Dim c As String = DirectCast(X, String)
    Do While m < 100
        SyncLock lobj1
            p = m
            m += 1
        End SyncLock
        Threading.Thread.Sleep(0) ' various calculations ...
        ' eventually
        'listL.Add(p.ToString & c) 'for debug
        listL.Add(p.ToString)
    Loop


    Debug.WriteLine("end " & c)

End Sub

End Module
于 2013-07-26T15:09:25.213 回答