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

标签 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 中创建的缓冲区本身的可见性?有必要吗?

最佳答案

如果您使用SetEvent,则根本不需要屏障。该事件负责处理这个问题。

通常,为了使障碍物具有明显的效果,您需要在两侧(书写面和阅读面)设置它们。由于 SetEvent/WaitForSingleObject 都充当障碍,所以没问题。

关于multithreading - _ReadWriteBarrier 是否确保跨线程动态分配的缓冲区的可见性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10843582/

相关文章:

c++ - 自旋锁定堆栈和内存屏障 (C++)

multithreading - 如何中断 UI 线程

visual-studio-2008 - 具有多个同名源文件的 Visual Studio 项目?

c++ - 为什么使用这两组语句时variable中的数据不同?

c++ - C++ 中的 typeid 运算符

java - 深入理解Java中的volatile

c++ - 多线程性能

c# - 什么可能是我的 C# WCF 服务上的速率限制 CPU 周期?

Java线程循环卡住程序

c# - 具有 volatile 或内存屏障的双锁