1

In C, when i have a shared object between many threads, but i can guarantee that it will not be modified, can i restrict-qualify a pointer to it? Of course, in each individual thread the usual requirement, that the pointer provides exclusive access to the object, holds. But considering all threads, the access isn't really exclusive anymore, since every thread has a pointer. Is it still valid to use restrict on this pointer?

Finn
  • 37
  • 5
  • 1
    The restrict qualifier is not much about how threads access data but whether multiple pointers reference the same object in a function independently of how thread access memory. If multiple threads access to the same object, you need atomics/barriers/mutexes/etc., and this defeat (nearly all) optimizations enabled by the use of the restrict keyword. If one thread write at a time, you still need at least memory barriers. You cannot modify data accesses by a thread on its back safely without synchronization mechanism (though most people do that). – Jérôme Richard Oct 09 '22 at 16:33
  • 1
    @Finn: Can you provide sample code to show what you mean? – Nate Eldredge Oct 09 '22 at 18:06

1 Answers1

0

If an object is not modified, then it is always fine to access it via a restrict-qualified pointer, no matter how many times or where it is done.

The semantics of restrict are defined in 6.7.3.1 p4 (C17 N2176):

During each execution of B, let L be any lvalue that has &L based on P. If L is used to access the value of the object X that it designates, and X is also modified (by any means), then the following requirements apply: [irrelevant]

Here an execution of B means that portion of the execution of the program that would correspond to the lifetime of an object with scalar type and automatic storage duration associated with B.

If your object X is not modified by any means during the execution of any block B where you would use the restrict pointer, neither by this thread nor any other, the requirements that follow do not apply, and there are no other requirements related to restrict that would apply.

(In a multi-threaded program, I presume the intended interpretation of "not modified during the execution of B" would be that any modifications of X must either happen before the evaluations in the block B, or vice versa.)

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
  • Thanks for the answer, that is what i intended. The block of code satisfies the normal requirements for restrict and the restrict-qualified objects are not modified. I just wondered, wheter multithreaded execution of this block makes a difference. – Finn Oct 11 '22 at 07:53