Search Unity

"Locking" a variable in a parallel job

Discussion in 'Entity Component System' started by Mr-Mechanical, Feb 17, 2019.

  1. Mr-Mechanical

    Mr-Mechanical

    Joined:
    May 31, 2015
    Posts:
    507
    I have this situation where multiple threads may attempt to access/modify a variable at the same time. Is there a way to "lock" a variable so it can only be accessed by one thread? Or is this sort of functionality exclusive to Native containers?

    Thank you advice is greatly appreciated
     
  2. Mr-Mechanical

    Mr-Mechanical

    Joined:
    May 31, 2015
    Posts:
    507
    I'm reading up on creating custom NativeContainers and it seems that this sort of stuff is intended to be encapsulated inside a container.
     
  3. GilCat

    GilCat

    Joined:
    Sep 21, 2013
    Posts:
    676
    I think you have to create your own native container with a concurrent version of it.
    You can find the documentation for it here
     
    Mr-Mechanical likes this.
  4. Abbrew

    Abbrew

    Joined:
    Jan 1, 2018
    Posts:
    417
    If your variable is a simple int or long, the Interlocked class may be of interest to you
     
    Mr-Mechanical likes this.
  5. Mr-Mechanical

    Mr-Mechanical

    Joined:
    May 31, 2015
    Posts:
    507
    I'm very interested in this, is there any documentation for the Interlocked methods?
     
  6. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
  7. Mr-Mechanical

    Mr-Mechanical

    Joined:
    May 31, 2015
    Posts:
    507
    Is it okay to use this Interlocked class outside of a Native Container implementation and do this directly in a parallel job's execute function?

    For example on an element of a nativearray?

    Thanks. This may be extremely helpful to me.
     
  8. Abbrew

    Abbrew

    Joined:
    Jan 1, 2018
    Posts:
    417
    Yes, for example you can have a IJobParallelFor that sorts a NativeArray into two NativeArrays based on a predicate. You can have two int* pointers, truePointer and falsePointer. Do Interlocked.Increment() on truePointer and store the element of the original array into one array if the predicate is true, and vice versa. This strategy isn't recommended because all the concurrent accesses of truePointer and falsePointer means a lot of resource contention, but you get the idea.
     
    Mr-Mechanical likes this.