Unexpected behavior when using dictionary with multithreading in swift

Viewed 30

I'm attempting to perform numerous asynchronous activities using dispatch queues. My biggest challenge was to have the threads access a dictionary while keeping it safe with an NSLOCK. At the start of my code, I initialized the dictionary so that it didn't have any nil values, and then the threads started accessing it. However, at some point, some threads read the value of the optional got from the dictionary as nil, even though it had been initialized and some previous threads accessed the same index and modified its value by simply subtracting one from it, making it impossible to turn to nil.

I suspected a race condition, so I converted the dictionary to a standard array using the same locking method, and everything worked properly on over 50 runs, and all of the final values saved on the array were consistent, indicating that no race condition occurred.

So, why did using the dictionary with the same locking technique cause certain threads to read the optional value as nil after a while?

0 Answers
Related