So its in C#, and basically I’ll have a position in an array for each thread to store some data. Would I Need to lock this? For example:
int[] threads = new int[12];
Each thread would access a specific position in the array for example, thread 1 will update the value in threads[0], thread 2 threads[1], etc.
Idea is to have the console print the values that are stored in the array.
Alright got so many comments. I thought I would clarify exactly what I am doing in the hopes I will learn even more. So basically the gist of it is:
The main thread kicks off 12 separate threads, each thread calls a function in the main thread to get a bunch of records from the database. The access to that method is locked but it returns about a 100 records for the thread to process by itself.
As the thread is processing the records it makes a couple of web requests and inserts into the database. Once the thread has finished processing its batch of records it calls a function again from the main thread and that function kicks off a new thread in lieu of the last one being finished.
As the threads are doing their processing I would like to output their progress in the console. Initially I locked each console output because if the same function gets called simultaneously the cursor position for each output would go all over the place. So I was thinking I would have an array that stored the counts for each value and then have a function just print it all out. Although I am starting to wonder if that would really be any different than what I currently am doing.
I believe that if each thread only works on a separate part of the array, all will be well. If you’re going to share data (i. e. communicate it between threads) then you’ll need some sort of memory barrier to avoid memory model issues.
I believe that if you spawn a bunch of threads, each of which populates its own section of the array, then wait for all of those threads to finish using
Thread.Join, that that will do enough in terms of barriers for you to be safe.MSDN documentation on Arrays says:
So no, they’re not thread safe. Generally a collection is said to be ‘not threadsafe’ when concurrent accesses could fail internally, but as each thread will access different possitions, there is no concurrent access here.