M
M
Mikhail2019-09-03 02:32:52
.NET
Mikhail, 2019-09-03 02:32:52

When multi-threaded work, the possibility of simultaneous access to resources is excluded?

I apologize in advance for the large amount of text. I learned quite a lot about threads. Understood with lock, monitors, semaphores and mutexes. I read about SynchronizationAttribute, volatility types and class Interlocked. All this is more or less clear to me, but there is a fundamental question that makes all other knowledge on the topic useless.
As I understand it, when I run multiple threads, they do not work at the same time. In fact, the processor first spends n seconds on one thread, then n seconds on another, and so on. This is called a context switch. But then it turns out that simultaneous access to a class variable from different threads is not possible? Indeed, in fact, we will simply first work with a variable from one thread for n seconds, then for n seconds - from another, and so on. By the same logic, it turns out that we can safely add data to the list and remove data from the same list from different threads ? But then it is not very clear why the classes from the namespace are needed System.Collections.Concurrent.
After reviewing the information, I remembered (but did not understand) that atomic operations are safe when running in multi-threaded code (is it so?). That is why, for example, incrementing a variable using Interlocked.Addis safe and does not lead to problems. The text turned out to be somewhat chaotic, so I will try to summarize:
1. If there is no simultaneity of the work of threads, then how is it possible to simultaneously change a variable from different threads?
2. Why are atomic operations always thread-safe?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Meloman19, 2019-09-03
@makarychev13

You do not quite understand the problem of multithreading. Yes, reading an immutable value from multiple threads is safe, but changing it is not.
For example: The
value is in memory . While it is only being read, everything is OK, but suppose that we have some kind of counter and two threads want to increase it by 1.x = 1
The first thread reads the value, pushes it onto the stack, adds 1, and then writes the result (2) back. You can see for yourself that there is by no means a single operation, and time passes between the moment of reading and writing. At this time, the second thread can easily have time to read the still old value. It turns out that both threads will take 1, increase it by 1 and write it to memory, no matter in what order. As a result, it seems like both threads completed the code, but the value in memory was increased by only 1. This is the problem.
Lists, for example, internally store the same counter for the number of elements, so concurrent writing may not work correctly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question