【问题标题】:How to modify a global array inside a multithreaded function如何在多线程函数中修改全局数组
【发布时间】:2018-08-10 01:20:10
【问题描述】:

我正在尝试向函数内的全局数组添加一个值。函数调用是多线程的,会瞬间调用函数的多个实例

每个线程都会修改数组,但会覆盖其他线程写入的数据。

我的代码如下:

Function QuickPing { 

    param ($LastByte) 
    $P = New-Object -TypeName "System.Net.NetworkInformation.Ping" 
    if(($P.Send("200.200.200.$LastByte")).status -eq "success"){
        echo "this one responded 200.200.200.$LastByte"
        $global:alive+="200.200.200.$LastByte" 
        $global:alive
    }
} 
$global:alive = @()


1..255 | Start-Parallel -Command QuickPing -MaxThreads 500 

write-host $alive

输出如下:

PS C:\WINDOWS\system32> E:\scripts_during_phase2\ping_array.ps1
this one responded 200.200.200.1
200.200.200.1
this one responded 200.200.200.17
200.200.200.17
this one responded 200.200.200.254
200.200.200.254


PS C:\WINDOWS\system32> $alive

PS C:\WINDOWS\system32> 

如上所示,每次调用该函数时,$alive 数组中的值都会被覆盖。

write-host $alive 命令运行时,我如何确保$alive 包含200.200.200.1,200.200.200.17,200.200.200.254

【问题讨论】:

  • Start-Parallel 似乎是基于RunspaceFactory Class 的自定义模块。实际上,设计 *Remember that RunSpaces don’t share anything* 中有一个明确的注释,这对于 RunSpaces 来说并不普遍,因为您可以与 SessionStateProxy Class 共享信息,但这显然没有在此解决方案中实现。

标签: .net windows multithreading function powershell


【解决方案1】:

使用锁。

https://en.wikipedia.org/wiki/Lock_(computer_science)

这将确保一次只有一个线程可以访问数组

【讨论】:

  • 你如何共享锁的状态?这基本上是一个Catch-22 解决方案,除非您进一步详细说明如何为这个问题实现它。
猜你喜欢
  • 2021-02-23
  • 2018-02-16
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多