I'm working with a list that is shared among many threads.
I believe that to a good performance in this case, it will be good to use InterlockedExchange function to insert data in this list, but I have some doubts.
If a thread tries to read a variable that is being written by another thread with InterlockedExchange, What will be the reaction? The thread that is reading the variable will wait for the completion of writing or will continue running and can not read the variable?
is necessary to use InterlockedExchange to read the variable when it is being written with interlockedechange?
How to test this function to try to know what will be the reaction to a multiple access to a shared variable between threads?
The reading thread will read either:
In fact this is true for plain read/write contention, that is if you are not using atomic functions. Memory access of machine word sized (or smaller) data is atomic. That is you are guaranteed not to have partial reads or rights. It must be the case that your variable is aligned, since you are using InterlockedExchange. Ergo, there can be no partials reads or writes, and hence no tearing.
Now, if your variable was not aligned, then a data race can lead to the read thread receiving part of the pre-write value, and part of the post-write value. That is known as tearing.
No. In fact that would not work. Because InterlockedExchange modifies the variable. And a read operation does not. Read the value with a plain memory read. That's the only way. Of course, you have a data race with the write thread, but that's inevitable.
I have serious doubts that your code correctly implements a lock-free container. Inserting an item into a lock free container is not easy to implement. In fact lock free containers are fiendishly difficult to implement. You need more than just calls to InterlockedExchange whenever you mutate the container.