Re: Class and Multi-thread safety



On 16 Out, 19:25, Jon Skeet [C# MVP] <sk...@xxxxxxxxx> wrote:
Nuno Magalhaes <nunommagalh...@xxxxxxxxxxx> wrote:
Is there any keyword applicable to a class to make it thread-safe?
Without having to put lock(this){} in all functions?

Putting lock(this) doesn't make it thread-safe.

Thread safety is not a simple matter - you need to carefully consider
threading and various issues when making a class thread-safe. In
particular, think about any code in other classes you call while
holding a lock - if you're not careful, you can easily deadlock.

I'd also recommend against locking on "this" to start with.

--
Jon Skeet - <sk...@xxxxxxxxx>http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

What is the difference between locking on "this" and locking on an
object inside the class? My object is never changed. What can go wrong?

.



Relevant Pages

  • Re: Trap when using Random() ... make sure it is not being changed too quickly
    ... declared within the same time slice will have the same seed. ... be careful of the fact that Random isn't thread-safe. ... and pieces here and there, and have sort of a 10000 m view, but if you ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Class and Multi-thread safety
    ... Putting lockdoesn't make it thread-safe. ... Thread safety is not a simple matter - you need to carefully consider ... holding a lock - if you're not careful, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: file offset corruption on 32-bit machines?
    ... I can easily imagine such a program. ... The easiest way to imagine a program not doing locking and being useful ... anyway (as long as the kernel is thread-safe) is to use the same arguments ... But he notices that the corruption isn't consistent with that hypothesis. ...
    (Linux-Kernel)
  • Re: locking
    ... > thread-safe is probably a much bigger task. ... I saw that the routing code seems to use macros for the locking ... Do you use macros everywhere? ... Regarding synchronization -- semaphores can be used to implement mutual ...
    (freebsd-net)
  • Re: Concurrency and delegates
    ... thread-safe, people do actually do _something_ like this. ... One technique I've seen suggested doesn't use locking at all. ...
    (microsoft.public.dotnet.languages.csharp)

Loading