我正在使用 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]);
}
我相信从保证地址可见性的文档中,就像一个全局变量一样。但它是否也保证了创建的缓冲区本身的可见性?甚至有必要吗?_ReadWriteBarrier
buff
buff
main