' Collection of code snippets by Arne Vajhøj 
' (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
﻿Imports System
Imports System.Threading

Namespace Correct
    Public Class Program
        Public Class Data
            Public Property S() As String
        End Class
        Public Class Processor
            Private d As Data
            Public Sub New(d As Data)
                Me.d = d
            End Sub
            Public Sub Run()
                ' simulate some work between get and set
                SyncLock d
                    Dim s As String = d.S
                    Thread.Yield()
                    d.S = s & "X"
                End SyncLock
            End Sub
        End Class
        Public Shared Sub Test(njobs As Integer, nthreads As Integer)
            ' setup data
            Dim d As New Data() With { .S = "" }
            ' process with shared data
            For i As Integer = 0 To njobs \ nthreads - 1
                ' create threads
                Dim t As Thread() = New Thread(nthreads - 1) {}
                For j As Integer = 0 To nthreads - 1
                    t(j) = New Thread(AddressOf (New Processor(d)).Run)
                Next
                ' start threads
                For j As Integer = 0 To nthreads - 1
                    t(j).Start()
                Next
                ' wait for threads to complete
                For j As Integer = 0 To nthreads - 1
                    t(j).Join()
                Next
            Next
            Console.WriteLine("{0} threads : expected = {1}, actual = {2}", nthreads, njobs, d.S.Length)
        End Sub
        Public Shared Sub Main(args As String())
            Test(2560, 1)
            Test(2560, 2)
            Test(2560, 4)
            Test(2560, 8)
            Test(2560, 16)
            Test(2560, 32)
            Test(2560, 64)
            Console.ReadKey()
        End Sub
    End Class
End Namespace
