开发者

Why are locks needed in an instantiated class? Doesn't every instance have its own data etc?

In C#, a class level variable would not be thread-safe (any exceptions to this? Let me know). So I would have to wrap the usage of this variable (like in a method in the same class), in a lock.

However, the very idea of using new makes me think that each class instance has its own instance etc a开发者_JAVA技巧nd one instance variable is never shared, so the calls to the method never see anything that is shared data. So why would an instantiated class need locks on its class-level variables? Locks are only needed when two threads access the same memory address, but I thought this would always not be the case?

Thanks


You can create an instance of a class, and access it from multiple threads. For example:

 MyClass classInstance = new MyClass();
 Task.Factory.StartNew( () =>
       {
             classInstance.DoSomething();
       });

 Task.Factory.StartNew( () =>
       {
             classInstance.DoSomething();
       });

Both of these tasks will execute on a background thread, and use the same instance - The one pointed to by "classInstance". This requires synchronization if the class is mutable.


The same object instance can have methods invoked by multiple threads at the same time.


Threads can share memory, which is what allows you to pass data back and forth. Processes prevent you from sharing memory directly. Because of this, another thread in the same process could in theory access a variable at the same time.


Locks are only needed when two threads access the same memory address, but I thought this would always not be the case?

It's not always the case, no, it depends on how you code your program.

If your program changes the same instance from different threads, you'll need some form of locking to prevent them from stepping on eachothers toes.

If you only access an instance of your class in one thread, you don't need locking.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜