Example 3
And one final example, to show that an optimization is disabled across an atomic operation.
Problem: Shared memory loads cannot be hoisted across atomic operations, verify that the optimization has been disabled.
- Set elements of an array to the value of a global variable in a loop which also contains an atomic operation.
- The 'other-thread' inferior function call increments the global variable each time.
- This should result in the value of 'global' being different every time an element of the array is stored.
- The 'final_verify' inferior function call checks to make sure that each element of the array has a different value. If any array values are the same, it indicates the load of the global was illegally reused, and the test case fails.
And the code looks something like:
int global = 0;
int sum[3] = { 0, 0, 0 };
atomic_int atomi;
/* Bump the value of global every cycle. */
void other_threads()
{
global++;
}
/* Nothing to check every cycle. */
int step_verify()
{
return 0;
}
/* Final result should have a different value of 'global' stored in each
* element, unless the load was hoisted. */
int final_verify()
{
if (sum[0] != sum[1] || sum[1] != sum[2] || sum[0] != sum[2])
return 1;
return 0;
}
/* 'global' is bumped by "the other thread" every insn.
* test is that all elements of 'sum' are different, otherwise the load of
* 'global' has been illegally hoisted across the atomic store. */
void test()
{
int x;
for (x=0; x< 3; x++)
{
atomic_store (&atomi, x);
sum[x] = global;
}
}
extern void done();
int main()
{
test();
done();
}