Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

should I insert MemoryBarrier?

I have such code:

.....
private volatile bool _connSharedDisposed;
......

    // Thread 1
    while (!_connSharedDisposed)
    {
        Thread.Sleep(1);
    }
    CGate.Close();

    ......
    // Thread 2
    _connShared.Close();
    _listenerFutInfo.Close();
    _listenerFutInfo.Dispose();
    _listenerFutCommon.Close();
    _listenerFutCommon.Dispose();
    _connShared.Dispose();
    // insert Thread.MemoryBarrier here?
    _connSharedDisposed = true;

I'm afraid that _connSharedDisposed = true might be rearranged and receive true before calling _connShared.Dispose(). Is it possible? If my code doesn't work how to fix it? I guess I probably should insert MemoryBarrier to block "rearrange"

Also probably I should use AutoResetEvent instead of bool volatile variable...

Upvotes: 0

Views: 145

Answers (1)

Peter Ritchie
Peter Ritchie

Reputation: 35869

If you've declared _connSharedDisposed with volatile, there's no need to use MemoryBarrier.

volatile makes each every write to a the field a volatile write and every read to the field a volatile read. this means that the compiler cannot re-order instructions so that the order of accesses to the field remain the same in relation to one another.

On processors other than x86, volatile also causes any CPU cached writes to be flushed to RAM. If you compile for x86, then volatile only applies to compiler optimizations.

If what you're trying to do is to cause a single thread to go into a wait state until something happens, then an auto reset event would be something you could use instead. AutoResetEvent is the class that models this. If you want to allow multiple threads to stop waiting, a manual reset event may be a better choice. ManualResetEvent or ManualResetEventSlim (in .NET 4.0 or newer) are the classes that models that.

Upvotes: 2

Related Questions