Previous: Inheritance Up: Atomicity Next: Examples
The following issues should be kept in mind when using atomic functions.
class Trouble {
private:
int x;
public:
atomic void assign (int i)
{ x = i; }
atomic int check (void)
{ return x; }
};
int main()
{
Trouble t;
t.assign(0);
par {
t.assign(1);
while (t.check()!=1) {}
}
...
}
Though the language guarantees that eventually operations from both threads of control in the parallel block will get a chance to execute, there is no guarantee about how soon an operation from a particular thread (say the first one, which assigns 1 to t.x) will be chosen. Thus, we cannot be guaranteed to observe the termination of this parallel block.
class Protect {
private:
int x;
public:
atomic void write (int i) { x = i; }
int read (void) { return x; }
};
To rectify the problem, the member function read() should be declared atomic as well. (Of course, there is no problem if the class is used in a manner that guarantees that no instance of write() is composed in parallel with any instances of read().)