In Powershell, is there a way to increment a variable from multiple threads safely.
I thought the below code using System.Threading.Interlock::Add
would work, but the output shows thread mashing is occurring.
# Threads will attempt to increment this number
$testNumber = 0
# Script will increment the test number 10 times
$script = {
Param(
[ref]$testNumber
)
1..10 | % {
[System.Threading.Interlocked]::Add($testNumber, 1) | Out-Null
}
}
# Start 10 threads to increment the same number
$threads = @()
1..10 | % {
$ps = [powershell]::Create()
$ps.AddScript($script) | Out-Null
$ps.RunspacePool = $pool
$ps.AddParameter('testNumber', [ref]$testNumber) | Out-Null
$threads += @{
ps = $ps
handle = $ps.BeginInvoke()
}
}
# Wait for threads to complete
while ($threads | ? {!$_.Handle.IsCompleted }) {
Start-Sleep -Milliseconds 100
}
# Print the output (should be 100=10*10, but is between 90 and 100)
echo $testNumber