bhawley
bhawley

Reputation: 425

Is NULL checking across ONLY 2 threads thread-safe?

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

Answers (3)

Robert Jacobs
Robert Jacobs

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

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

Cloud
Cloud

Reputation: 19331

No, as the assignment = operation is not atomic.

Upvotes: 3

Related Questions