#StackBounty: #ios #swift #multithreading #concurrency Safety of using an empty reference instance across multiple threads

Bounty: 150


I have a class Data that stores multiple input parameters and a single output value.

The output value is recalculated whenever one of the input parameters is mutated.

The calculation takes a non-trivial amount of time so it is performed asynchronously.

If one of the input parameters changes during recalculation, the current calculation is cancelled, and a new one is begun.

The cancellation logic is implemented via a serialized queue of calculation operations and a key (reference instance) (Data.key). Data.key is set to a new reference instance every time a new recalculation is added to the queue. Also only a single recalculation can occur at a time — due to the queue. Any executing recalculation constantly checks if it was the most recently initiated calculation by holding a reference to both the key that what was created with it when it was initiated and the currently existing key. If they are different, then a new recalculation has been queued since it began, and it will terminate.

This will trigger the next recalculation in the queue to begin, repeating the process.

The basis for my question

The reassignment of Data.key is done on the main thread.

The current calculation constantly checks to see if its key is the same as the current one. This means another thread is constantly accessing Data.key.


Is it safe for me to leave Data.key vulnerable to being read/written to at the same time?

Is it even possible for a property to be read and written to simultaneously?

Get this bounty!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.