What is threadfence_block?

void __threadfence_block();

is equivalent to cuda::atomic_thread_fence(cuda::memory_order_seq_cst, cuda::thread_scope_block) and ensures that:

  • All writes to all memory made by the calling thread before the call to __threadfence_block() are observed by all threads in the block of the calling thread as occurring before all writes to all memory made by the calling thread after the call to __threadfence_block();
  • All reads from all memory made by the calling thread before the call to __threadfence_block() are ordered before all reads from all memory made by the calling thread after the call to __threadfence_block().

What does this mean…Too complicated like a Tongue Twister

I am trying to understand it… It seems that even the code is like

x=1;
y=2;

But the actually action sequence might be different, maybe first execute y=2, and then x=1(because Out-of-Order Instruction Execution)?? Only if we add a threadfence(),

x=1;
threadfence();
y=2;

and this can guarentee, first x=1, and wait it finished, and then we execute y=2???

It’s a statement/guarantee of (ordering of) visibility.

When I do:

x=0;
y=0;
x=1;
y=2;

There is no guarantee that some other thread reading those locations (x, and y, for the sake of discussion here in global or shared memory) might in one instant read y as 2 and then in some later instant read x as 0. Such an outcome would be odd but possible.

OTOH if I do this:

x=0;
y=0;
x=1;
__threadfence();
y=2;

Then it is guaranteed that if some other thread read y as 2, and they subsequently read x, it is guaranteed that they would read x as 1 and not 0.

When you do __threadfence(), that guarantee is provided to any other thread in the grid. when you do __threadfence_block() that guarantee is only extended to other threads in the same block as the one writing to x and y.

Note that threadfence() in the above example does not guarantee that some other thread will read y as 2, or any other such thing. It only makes the conditional guarantee that I stated: IF another thread reads y as 2, it will not read x as 0.

This type of guarantee could be useful in some situations. For example suppose I have a buffer in memory, and a location in that buffer that indicates readiness to consume.

Suppose I fill the buffer first (lets say from a single thread) and then from that same thread I do a threadfence followed by a write to the location indicating readiness to consume.

Now, if some other thread is monitoring that readiness location, and observes the readiness indicator/value, they will have a guarantee that the previous writes to the buffer are also properly visible.