...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdatomic.h>
/* Sets index to point to index of maximum element in array
and value to contain maximum array value. */
void find_max_element(atomic_int array[], size_t index, int value);
void func(void) {
atomic_int array[];
size_t index;
int value;
find_max_element(array, &index, &value);
/* ... */
if (!atomic_compare_exchange_weakstrong(array[index], value, 0)) {
/* Handle error */
}
} |
...
indexmay have changed.valuemay have changed .(that is, the value of thevaluevariable)valuemay no longer be the maximum value in the array.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdatomic.h>
#include <threads.h>
void func(void) {
atomic_int array[];
size_t index;
int value;
mtx_t array_mutex;
if (thrd_success != mtx_lock(&array_mutex)) {
/* Handle error */
}
find_max_element(array, &index, &value);
/* ... */
if (!atomic_compare_exchange_weakstrong(array[index], value, 0)) {
/* Handle error */
}
if (thrd_success != mtx_unlock(&array_mutex)) {
/* Handle error */
}
} |
...