简体   繁体   中英

What does it mean to make static data thread-safe by default?

I want to preface my question with the claim that I understand thread synchronization primitives and my question is not about how to use them. It is merely a clarification of a statement I read from the MSDN.

The Managed Threading Best Practices page, towards its very end, states as one of the bullet points, the following:

Make static data (Shared in Visual Basic) thread safe by default.

What does that mean? Does it mean there is a way to make static data thread-safe without the use of any thread synchronization code? If so, how?

class Foo
{
  // How do you make this thread-safe without thread sync code?
  static int x;

  static void Do()
  {
    // This, I understand, is thread-safe, by default.
    int y;
  }
}

Thanks to the commentators on the question for their guidance. I am posting this as an answer to anyone who might have this same confusion.

Reading the very next line makes it somewhat clear that the implication is that we must use thread synchronization code to ensure the thread-safety of static data in particular.

While we must also be careful of sensitive instance data that might be amenable to multiple thread usage, it is better to arrive at a trade-off on the level of synchronization code we would write for protecting instance data as it may adversely affect performance.

The very next point reads as follows:

Do not make instance data thread safe by default. Adding locks to create thread-safe code decreases performance, increases lock contention, and creates the possibility for deadlocks to occur. In common application models, only one thread at a time executes user code, which minimizes the need for thread safety. For this reason, the .NET Framework class libraries are not thread safe by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM