refcount – Atomic Reference Counting C API (User)



Name

refcount_add_swap_weak(…) – add and swap reference (strong/basic thread-safety)


Synopsis

#include < refcount.h >

refcount_t* refcount_add_swap_weak(refcount_t* volatile *psloc, refcount_t *xchg, int count);


Description

The refcount_add_swap_weak (…) function is used to swap the reference to a refcount_t object from a shared location with another reference or NULL and transfer the previous value, if it’s not NULL, to the calling thread. This function guarantees that the entire reference swap operation is atomically thread-safe and will strictly adhere to a thread-safety level of strong. This function guarantees that the reference increment operation, if any, is atomic and will strictly adhere to a thread-safety level of basic.

The ‘psloc’ parameter MUST point to a shared location in memory that contains either a pointer to a refcount_t object or NULL. The ‘xchg’ parameter MUST be NULL or point to a refcount_t object that MUST be acquired by or transferred to the calling thread before it calls into this function. The ‘count’ parameter MUST be a value that is greater than or equal to 0. The caller will be subjected to undefined-behavior if the ‘psloc’, ‘xchg’ or ‘count’ parameters contain any values that violate those rules.

The function WILL always swap the contents of the shared location pointer to by ‘psloc’ with ‘xchg’. If ‘xchg’ is not NULL and ‘count’ is greater than 0 the function guarantees that the previous reference count of the reference pointed to by ‘xchg’ will have been atomically incremented by ‘count’.

If the function fails, that means that ‘psloc’ pointed to a location that contained NULL. Please note that even though the function may fail and return NULL, if ‘xchg’ was not NULL and ‘count’ was greater than or equal to 0 then it guarantees that the reference count of the refcount_t object pointed to by ‘xchg’ will have been incremented by ‘count’ before it got swapped into the location pointed to by ‘psloc’.

Return Value

If successful, the refcount_add_swap_weak(…) function returns a pointer to the previous refcount_t object that occupied the location pointed to by ‘psloc’. In this case, the returned refcount object has been successfully transferred to the calling thread. Otherwise, it will return NULL; refer to the Errors for more information…


Errors

The refcount_add_swap_weak(…) function will fail if:

[NULL] - The shared location pointed to by ‘psloc’ contained NULL. Remember to keep in mind that if ‘xchg’ and ‘count’ are valid values (e.g., ‘xchg’ != NULL && ‘count’ >= 0) then the reference count increment WILL still proceeded even though the function failed by returning NULL.

[Undefined Behavior] - The values of ‘psloc’, ‘xchg’ or ‘count’ were invalid.