简体   繁体   English

多线程'固定'

[英]Multi-threaded 'fixed'

I have a huge array that is being analyzed differently by two threads: 我有一个庞大的数组,由两个线程进行不同的分析:

  • Data is large- no copies allowed 数据很大 - 不允许复制
  • Threads must process concurrently 线程必须同时处理
  • Must disable bounds checking for maximum performance 必须禁用边界检查以获得最佳性能

Therefore, each thread looks something like this: 因此,每个线程看起来像这样:

unsafe void Thread(UInt16[] data)
{
  fixed(UInt16* pData = data)
  {
    UInt16* pDataEnd = pData + data.Length;
    for(UInt16* pCur=pData; pCur != pDataEnd; pCur++)
    {
      // do stuff
    }
  }
}

Since there is no mutex ( intentionally ), I'm wondering if it's safe to use two fixed statements on the same data on parallel threads?? 由于没有互斥( 故意 ),我想知道在并行线程上对相同数据使用两个固定语句是否安全? Presumably the second fixed should return the same pointer as the first, because memory is already pinned... and when the first completes, it won't really unpin memory because there is a second fixed() still active.. Has anyone tried this scenario? 大概第二个修复应该返回与第一个相同的指针,因为内存已被固定...当第一个完成时,它不会真正解除内存,因为还有第二个fixed()仍处于活动状态..有没有人试过这个场景?

According to "CLR via C#" it is safe to do so. 根据“CLR via C#”,这样做是安全的。

The compiler sets a 'pinned' flag on pData variable (on the pointer, not on the array instance). 编译器在pData变量上设置'固定'标志(在指针上,而不是在数组实例上)。

So multiple/recursive use should be OK. 所以多次/递归使用应该没问题。

Maybe instead of using fixed, you could use GCHandle.Alloc to pin the array: 也许不使用fixed,你可以使用GCHandle.Alloc来固定数组:

// not inside your thread, but were you init your shared array
GCHandle handle = GCHandle.Alloc(anArray, GCHandleType.Pinned);
IntPtr intPtr = handle.AddrOfPinnedObject();


// your thread
void Worker(IntPtr pArray)
{
  unsafe
  {
     UInt16* ptr = (UInt16*) pArray.ToPointer();
      ....
  }
}        

If all you need to do is 如果你需要做的就是

 for(int i = 0; i < data.Length; i++)
 {
     // do stuff with data[i]
 }

the bounds check is eliminated by the JIT compiler. JIT编译器消除了边界检查。 So no need for unsafe code. 所以不需要不安全的代码。

Note that this does not hold if your access pattern is more complex than that. 请注意,如果您的访问模式比这更复杂,则这不成立。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM