Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

What is atomic_compare_exchange_weak in C?

Adnan Abbas

The atomic_compare_exchange_weak function compares memory contents that are pointed to by two different objects.

Syntax

bool atomic_compare_exchange_weak( volatile A* obj, C* expected, C desired );

The function compares the value of obj with expected, and if they are bitwise equal, it replaces the value contained in obj with desired value. Otherwise, it replaces the value pointed by expected with the one contained in obj by performing a load operation.

The operation of the function described above, where it reads and replaces data is atomic. This means that other threads cannot change the value between the time it is read and replaced.

This function reads and compares the actual contents on the disk of the value contained in obj and the value pointed by expected. The comparison may fail for some values that compare using the == operator.

Unlike its counterpart, atomic_compare_exchange_strong, this function is allowed to fail spuriously. This means that it can act as if *obj != *expected even if they are the same and return false. Such behavior might be acceptable for certain algorithms that involve loops, which will to better performance on some platforms.

Parameters

  • obj is a pointer to an atomic object to be compared.
  • expected is a pointer to the value which is to be compared with the one contained in obj.
  • desired is the value to store in obj if the comparison is successful.

Return value

The function returns true if the values pointed by obj and expected are equal; otherwise, it returns false.

RELATED TAGS

CONTRIBUTOR

Adnan Abbas
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring