_ReadWriteBarrier是否确保跨线程的动态分配缓冲区的可见性?

时间:2012-06-01 02:10:54

标签: multithreading visual-c++ memory-barriers

我正在使用Visual C ++和Windows 7和XP。我在程序中有两个线程,在创建两个线程之后,一个线程动态创建一个缓冲区并将其地址分配给全局指针,然后将数据写入该缓冲区。调用_ReadWriteBarrier会保证该数据对第二个线程的可见性吗?

例如:

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]);
}

我相信the documentation _ReadWriteBarrier保证buff中地址的可见性,因为buff是全局变量。但是它是否也保证了main中创建的缓冲区本身的可见性?它甚至是必要的吗?

1 个答案:

答案 0 :(得分:2)

如果您使用SetEvent,则根本不需要屏障。该活动负责照顾。

通常,对于具有可见效果的障碍,您需要在两侧(书写和阅读侧)。由于SetEvent / WaitForSingleObject都可以作为障碍,你很好。