Previous: Examples Up: Examples Next: Finding the Minimum Element

Hello World

This program is a variation on the traditional greeting program presented as the first example of Chapter .


#include <iostream.h> 
#include <string.h>

class Greeting { private: char* s;

public: Greeting (void) { s = new char[20]; } atomic void append (char* add) { strcat(s,add); } void display (void) { cout << s << endl; } };

int main() { Greeting g; par { g.append("hello, "); g.append("world"); } g.display();

return 0; }

This program displays one of the two following messages: "hello, world" or "worldhello, ". This message is built up by appending strings to the private mutable variable g.s. These appends can be safely done in parallel because the function is atomic. We do not know, however, which append will be performed first. The two possible interleavings of these append operations result in two different messages which can be displayed. Notice that display() is not atomic. This is not a problem because the program does not compose any operations in parallel with display().

paolo@cs.caltech.edu