gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:00:45 25 4
gpt4 key购买 nike

我正在使用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com