I create a thread container just like an read only UnsafeList witch element is NativeList(UnsafeList<NativeList>).
When you create one, you create serval NativeList for every single thread.
[NativeSetThreadIndex]
private int threadIndex;
private UnsafeList<NativeList<T>> threadList;
private Allocator _containerAllocator;
public ThreadList(Allocator allocator,Allocator containerAllocator = Allocator.Temp)
{
threadList = new UnsafeList<NativeList<T>>(JobsUtility.ThreadIndexCount, allocator);
for (int i = 0; i < JobsUtility.ThreadIndexCount; i++)
{
threadList.Add(default);
}
threadIndex = 0;
_containerAllocator = containerAllocator;
}
When you need a NativeList, call
public ref NativeList<T> CreateListRef(int capacity)
{
ref var list = ref threadList.ElementAt(threadIndex);
if (!list.IsCreated)
{
list = new NativeList<T>(capacity, _containerAllocator);
threadList[threadIndex] = list;
}
else if (list.Capacity < capacity)
{
list.Capacity = capacity;
}
list.Clear();
return ref list;
}
. therefore every thread use there own single NativeList.
I use it in some different way.
1ăUse it like container pool. Create in job with temp allocator in the first call, when it is created already, just clear. Itâs temp allocator so I donât dispose it in job. Just dispose threadList out of job which allocated by tempjob allocator.
2ăUse it like parallel collecter. Create in job with temp allocator in the first call, donât clear in next call. Collect all data in every thread out of job. Itâs thread safe because every thread has there own list. However, I need read data out of job, so I need create NativeList with tempjob allocator and dispose them when I dispose threadList.
thereâs some question:
1ăWhen I allocate temp NativeList in job and Dispose it out of the job, It throw an exciption âallocator handle is not validâ. I correct it by if (_containerAllocator is not (Allocator.Temp or Allocator.None or Allocator.Invalid))
. But I still donât know why and what happend.
2ăIs it safe when a allocate tempJob memory in job and dispose it out of job?