我使用的是 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/