I had a conversation with a few co-workers and the concept of thread safety for a data structure came up.
In this example, we have 2 threads: a main thread and a background thread.
For the following pseudo class:
class Foo {
Array myArray;
// Only ever called on the main thread
// This method will call into the background thread
// but when complete the onCompleteBlock will be called
// on the main thread.
function method1() {
// do something to the array on main thread
myArray.add('foo');
callBackgroundThread(onComplete() {
// onComplete callback is called on main thread
// do something else to the array on the main thread
myArray.add('bar');
})
}
// only ever called on the main thread
function method2() {
// do some other stuff to the array on the main thread
if (myArray.contains('bar') {
myArray.remove('foo');
}
}
}
So in this example the class has an array as a data structure. Both methods are always guaranteed to be called on the main thread. Method1 calls a function that kicks off a background process, when that process is finished it calls back into the main thread.
Is this class, and the myArray data structure 'safe'?
I know this class is not thread safe as the myArray data structure is not protected by any synchronization. So if multiple threads did call method1 and method we would run into trouble. But any time myArray is used, it is used on the main thread.
One argument on why this might not be safe is that if the main thread is paused (like when we are in the background thread), it may not be resumed in the same place it left off, i.e. maybe an operation called method2() and that is where the main thread wakes up and resumes.
Another is that memory may have been swapped. Not sure what was meant by this.
To be fair, I did not fully understand either argument and thought that this class was fine since all variables were only accessed on the main thread. If either argument above is true can someone please help explain further? I thought that making sure to modify data on the same thread would be safe.