D

변수에 값을 쓸 때는 락을 걸어야 한다 1

fullnessfruit 2023. 11. 28. 17:39

안다고 생각했던 게 헷갈릴 때가 있다.

https://stackoverflow.com/questions/3580291/what-happens-if-two-threads-read-write-the-same-piece-of-memory/3580312#comment3755597_3580312

 

What happens if two threads read & write the same piece of memory

It's my understanding that if two threads are reading from the same piece of memory, and no thread is writing to that memory, then the operation is safe. However, I'm not sure what happens if one t...

stackoverflow.com

 

C# 같은 언어의 경우 일부 자료형은 항상 atomic 하게 연산되기도 한다. 하지만 그렇다 하더라도 volatile 을 사용하면 성능이 저하될 수 있고 캐시의 값이 메모리에 즉시 반영되지 않을 수도 있는 문제 때문에 결국 락을 걸던가 해야한다.

 

https://learn.microsoft.com/en-us/dotnet/api/system.threading.interlocked.increment

 

Interlocked.Increment Method (System.Threading)

Increments a specified variable and stores the result, as an atomic operation.

learn.microsoft.com

https://learn.microsoft.com/en-us/dotnet/api/system.threading.volatile

 

Volatile Class (System.Threading)

Contains methods for performing volatile memory operations.

learn.microsoft.com