Menu

How are you supposed to prevent false sharing in C#?

Reddit r/csharp·u/AmCHN·5 months ago
#iJrRo0x4
#sharing#false#cache#alignment#prevent
Reading 0:00
15s threshold

Sorry if everything below sounds like a rant, but I stumbled on this question and felt that "I have to be missing something obvious".

How are you supposed to prevent false sharing (multiple threads accessing the same cache line) in C#?

"Not having multiple threads accessing adjacent fields/indices at the same time" is obvious, but the beginning of your struct can easily share one physical cache line with the end of another struct, especially with a moving GC (which AFAIK none guarantees alignment)?

Padding/StructLayout mitigate internal false sharing, but they don't stop your structs from sharing a cache line with another heap-allocated object...

... unless you control the alignment, but you don't...

... unless you use unmanaged memory...

... but if "use unmanaged" is the only answer to prevent false-sharing (which is a key & pervasive concern in high-performance parallel computing), why would you use C# in the first place?…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.