In particular, I want to set a value of a function pointer. For simplicity, I want to do it many times, from multiple threads, but always in a simple manner like this:
typedef void (*F)();
F f = 0;
void foo()
{
}
// called many times from multiple threads
void set()
{
f = &foo;
}
int main()
{
set(); // also other threads can invoke it at any time
f();
return 0;
}
Thus, initially the function pointer is NULL and then becomes &foo when the code is executed for the first time. I wonder if due to any non-atomic write operation the function pointer may become disrupted.
It is guaranteed that it will be read for the first time after it is set.
EDIT: I clarify:
- The main reason I use a function pointer is to remove some dependencies between modules. This is a small element of a big real project. I really can't call 'foo' directly.
- I know how to program and I do not need basic information about things like mutex. My question is whether this is safe WITHOUT mutex.
- It is guaranteed in the code that no other thread sets the pointer to anything other than &foo.