This seems like an XY problem.
It's a bit unclear what you're asking - my understanding is you want to access a
from different threads (maybe on different cores or even processors), so you're wanting to make sure it gets written out to RAM, rather than just cached or reused from a register. Is that right?
Concurrency is kind of a big topic and we don't know the details of the system you're running - when the two functions are called in relation to each other.
First things first - what you're starting to get at is the volatile
keyword. Declaring the variable as volatile int32_t* a;
tells the compiler it might be changed at any time from another thread, but doesn't guarantee anything about its status in memory vs the cache. If the 2 threads are known to be running on the same core and you're sure you'll be reading from a
after you've set it in main()
.
If you're not sure about which order the read & write will execute, you'll need to do your own thread synchronisation, which works differently depending on which architecture & libraries you're using. In general, you'd want something like this psuedocode:
int32_t* a;
semaphore_t aIsValid;
void main()
{
a = (int32_t*)malloc(4);
signal_semaphore(aIsValid);
}
void mainBis()
{
wait_for_semaphore(aIsValid);
// read from a
}
On most modern systems, using synchronisation primitives like semaphores also ensures cache coherence between threads, so a
will have the same value everywhere after aIsValid
releases.