How do I know if I have to care about thread safety?

I don’t know much about how computers work internally, so I also don’t know much about multithreading, and when it takes place. I know it is important in databases or web applications and such, where a lot of different machines try to access or modify the same resources, but what about “classic” code, like calculations?

I thought about using LinkedList in my code but I read it is not thread-safe (C#). So the question is if I even have to care.

The concrete problem is this: I have a class Interval that represents closed intervals, internally stored as two double values (lower and upper bound). I have a method that takes one interval I and a list L of disjoint intervals in ascending order. The method modifies L such that it is equivalent to joining the intervals of the list with I; the order is preserved.


L is: [-3, 0], [2, 4], [5, 18], [21, 22]
I is: [3, 6]
resulting modified L: [-3, 0], [2, 18], [21, 22]

The algorithm finds certain border intervals (the leftmost and rightmost interval of L that intersect with I, and the intervals next to these two), Removes all intervals between them and Adds a new interval between them. So this is the place where I need to know if thread-safety is a thing here.

So, how do I know?

You need to care about thread safety if you have multiple threads accessing the same shared (mutable) data structure. If the algorithm you describe runs in a single thread, you dont have to worry.

An ordinary C# program is single-threaded by default. You have to actively start new threads in order to get a multithreaded program. If you dont do that, you are safe.


You’re not talking of how many threads are doing work here, and which are doing what work. If this is a single thread, you don’t have to worry about thread safety.

When do you have to worry about thread safety then?

When you have multiple threads accessing the same data structure, and at least one of those threads are modifying it. So:

If you only read the data: No problem
If you only have one thread: No problem
If you modify the data while other threads might access it: Might be problems


Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *