Thursday 29 May 2014

Arrays are implicitly thread-safe

I am currently tasked with writing to a 2-dimensional array from multiple threads. Let me briefly explain the context of the problem.

I have a 2-D array which looks somewhat like this:

__ __ __ __ __
__ __ __ __ __
__ __ __ __ __
__ __ __ __ __
__ __ __ __ __
__ __ __ __ __
__ __ __ __ __
__ __ __ __ __

So, what I had to do was use 8 threads, one each to write to each row of the array. I was thinking whether I would need to synchronize write access to the array wherein each thread is writing to a separate memory space independent of the other threads. While the array itself is common for the threads, we can see that each thread is in fact writing to a different space and no thread is dependent on any other thread for reads/writes.

As I had expected, you do not need synchronization in such a scenario. While it may sound really trivial, sometimes basic concepts like these keep you thinking and wondering till you figure out that common sense is indeed the best friend.


No comments:

Post a Comment