Stevens Miller
Stevens Miller

Reputation: 1480

Does _ReadWriteBarrier Ensure Visibility of Dynamically Allocated Buffers Across Threads?

I am using Visual C++ and Windows 7 and XP. I have two threads in a program where, after both are created, one thread dynamically creates a buffer and assigns its address to a global pointer, then writes data to that buffer. Will a call to _ReadWriteBarrier guarantee the visibility of that data to the second thread?

For example:

char *buff;
HANDLE EventObject;

main()
{
    // Create an event object so we can signal the second thread
    // when it is time to read the buffer.

    EventObject = CreateEvent(NULL, TRUE, FALSE, NULL);

    // Create the second thread.

    CreateThread(NULL, 0, ThreadProc, NULL, 0);

    // Allocate the buffer.

    buff = (char*)malloc(100);

    // Write some data to the buffer.

    buff[50] = rand() % 256;

    // Set the fence here.

    _ReadWriteBarrier();

    // Signal the other thread that data is ready.

    SetEvent(EventObject);

    // Go on our merry way in this thread.
    .
    .
    .
}

ThreadProc(void* p)
{

    // Wait for the signal that data is ready.

    WaitForSingleObject(EventObject, INFINITE);

    // Read the data written to the buffer.

    printf("%d\n", buff[50]);
}

I believe from the the documentation that _ReadWriteBarrier guarantees the visibility of the address in buff, as buff is a global variable. But does it also guarantee the visibility of the buffer itself, that was created in main? Is it even necessary?

Upvotes: 2

Views: 607

Answers (1)

Ringding
Ringding

Reputation: 2856

If you use SetEvent, you don't need to have the barrier at all. The event takes care of that.

Usually, for barriers to have a visible effect, you need them on both sides (the writing and the reading side). Since SetEvent/WaitForSingleObject both act as barriers, you're fine.

Upvotes: 2

Related Questions