Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are memory-barriers required when joining on a thread?

If a thread A spawns another thread B with the single purpose of writing to a variable V and then waits for it to terminate, are memory-barriers required to ensure that subsequent reads of V on thread A are fresh? I'm unsure if there any implicit barriers in the termination / joining operations that make them redundant.

Here's an example:

public static T ExecuteWithCustomStackSize<T>
    (Func<T> func, int stackSize)
{
    T result = default(T);

    var thread = new Thread(
        () => 
                {
                    result = func();
                    Thread.MemoryBarrier(); // Required?
                }
        , stackSize);

    thread.Start();
    thread.Join();

    Thread.MemoryBarrier(); // Required?
    return result;
}

Are are either / both (or more) of the barriers in the above snippet required?

like image 744
Ani Avatar asked Oct 06 '22 15:10

Ani


1 Answers

No, synchronization mechanisms generate implicit memory fences. All data modified by a thread will be visible after the thread is joined.

like image 107
Tudor Avatar answered Oct 11 '22 00:10

Tudor