#ThreadSave Stack

1 messages · Page 1 of 1 (latest)

echo pollen
#
public struct Stack32
{
    public NativeArray<int> stack;
    public int size;
    public int count;
    public Stack32(int size)
    {
        this.size = size;
        this.count = 0;
        stack = new NativeArray<int>(size, Allocator.Persistent);
    }
    public void Fill()
    {
        for (int i = 0; i < size; i++)
        {
            Push(i);
        }
    }
    public void Push(int i)
    {
        stack[count] = i;
        count++;
    }
    public int Pop()
    {
        count--;
        return stack[count];
    }
    public NativeArray<int> PopRange(int ammount)
    {
        NativeArray<int> memory=new NativeArray<int>(count, Allocator.Temp);
        for(int i=0; i < ammount; i++)
        {
            memory[i] = Pop();
        }
        return memory;
    }
    public void Destruct()
    {
        stack.Dispose();
    }

}

I need help making my stack ThreadSave

dry path
#

just had a quick google and this is a native stack implementation i found

echo pollen
#

thank you but I don t understand that code

dry path
#

making stuff threadsafe is hard

echo pollen
#

this seems to be using unsafe code, which I am not

#

Im not familiar with unsafe code yet

dry path
#

then just send it into a job and copy it and then pop from the copy

echo pollen
#

I'd need to pop and push to it from multiple times

dry path
#

writing and reading at the same time isnt threadsafe for any of the native containers (except NativeStream in some circumstances)

echo pollen
#

Then what does threadsave mean, I thought you'd just have to lock the Stack32 struct when pushing or reading from it

dry path
#

locking is a bit different

#

that forces all the threads trying to access something to wait while another thread is accessing it

echo pollen
#

so it's making everything very slow right?

dry path
#

yup

#

i've not tried to use locks with jobs or native containers, it is against the design philosophy

echo pollen
#

so ur saying that without using nativecontainers it would be easyer to make it threadsave?

dry path
#

well you need native containers if you are using jobs, i was just saying that i've never used locks with them

#

well, it'd just be better for you to rethink your logic of needing to read and write in the same job