I want 500 objects to be processed concurrently using multithreading. These objects will have some initial data before the threads are created.
I am creating 5 threads and each thread takes 100 objects and starts the operation.
Here is the code.
public class InputData
{
public string initialData {get; set;}
public string formula {get; set;}
public string resultData {get; set;}
}
public static List<string> result = new List<string>(500);
public static void Main()
{
List<InputData> lst = new List<InputData>(500);
List<InputData> lst_1 = .. // This will hold 1 to 100 objects
List<InputData> lst_2 = .. // This will hold 101 to 200 objects
List<InputData> lst_3 = .. // This will hold 201 to 300 objects
List<InputData> lst_4 = .. // This will hold 301 to 400 objects
List<InputData> lst_5 = .. // This will hold 401 to 500 objects
Thread t1 = new Thread(Update);
...
...
Thread t5 = new Thread(Update);
t1.Start(lst_1);
...
t5.Start(lst_5);
//while condition to wait for the threads to finish processing
while(...)
{
..
}
}
public static void Update(List<InputData> lstAll)
{
lstAll.resultData = lstAll.initalData + lstAll.formula;
//result.Add(lstAll.resultData);
}
As you can see from the code, each thread uses a bunch of objects. And I am updating only the resultData
property of each object.
Is locking needed in this program? Can anyone please help
.net version is 3.5
7
You will need to analyze it like peeling an onion.
Changing the properties of objects that are stored within a List<>
will not cause its index position to shift. It will not cause the List<>
to perform any reallocations either.
Therefore, If the List<>
are not being modified (objects inserted, deleted, moved, or replaced), then:
(1) you are right in that using List<>
that is fully pre-initialized with objects would be sufficient.
But (2) you should then look at the next layer: does the computation of each object have any possibility of interfering with each other. Since we cannot see the code for the computation, we can’t comment on that.
This analysis is only applicable to the List<>
implementation provided in the .NET framework. If someone implements its own IList<>
, with non-trivial logic and behaviors (such that they do not mimic the behaviors of the standard implementation at all, say, by autonomously modifying the ordering or index positions of objects) then the analysis does not apply.
3
As long as all of your five lists above contain disjoint sets of objects, and as long as the line
result.Add(lstAll.resultData);
is commented out, there is no locking needed. But I guess you are telling us not the whole story, the program above in the current form does not make much sense, since any results are thrown away after processing. So tell us how and in which thread you intend to aggregate the results, then you might get better answers.
1