Tuesday, June 8, 2010

Synchronization

A classic problem related to synchronization is reader-writer problem, in which multiple readers and writers try to access a shared memory location. The shared memory access by reader and writers can be protected straightaway with a mutex, but that solution will not be optimal, since it doesn't make sense to block readers when there are no writers.

In the first reader-writer problem, the reader are given priority over writer and is solved like this:

Mutex m, local
int reader_count;

//Readers access

Wait(local); //Acquires a mutex
reader_count ++;
if(reader_count == 1) Wait(m);
Signal(local); //Release a mutex

....
...
...


Wait(local);
reader_count --;
if(reader_count == 0) Singal(m);
Signal(local);

//Writer Access
Wait(m);

...
...
...

Signal(m);

No comments:

Post a Comment