Reputation: 425
Given the following scenario:
Is it thread safe to have the reader thread check for null of the variable? Explicitly in a C program?
Example code:
Thread 1:
void initOnStartup()
{
ptr = malloc(10);
}
Thread 2:
void waitingForValue()
{
while(!ptr);
}
Upvotes: 3
Views: 141
Reputation: 3360
It is not atomic. Newer versions of C (and c++) provide the following. http://en.cppreference.com/w/c/atomic/atomic_store
void atomic_store( volatile A* obj , C desired); // (since C11)
void atomic_store_explicit( volatile A* obj, C desired, memory_order order ); // (since C11)
Upvotes: 3
Reputation: 8059
The answer is there: Is changing a pointer considered an atomic action in C? Unfortunately it isn't. Think of far pointers on 16 bit x86 platforms.
Upvotes: 2