Intel® Moderncode for Parallel Architectures
Support for developing parallel programming applications on Intel® Architecture.
1696 Discussions

reader_writer_mutex with no memory barriers on reader side

Dmitry_Vyukov
Valued Contributor I
273 Views

reader_writer_mutex with no memory barriers on reader side. No joke!

Here is the sketch:

class rw_mutex_t
{
private:
mutex_t guard;
unsigned reader_count;
bool volatile writer_pending;

public:
rw_mutex_t()
: reader_count()
, writer_pending()
{}

void register_reader()
{
lock_t lock (guard);
++reader_count;
}

void unregister_reader()
{
notify_writer();
lock_t lock (guard);
--reader_count;
}

void reader_lock()
{
if (writer_pending)
{
notify_writer();
wait_for_writer_notification();
}
}

void reader_unlock()
{
}

void writer_lock()
{
guard.lock();
writer_pending = true;
wait_for_all_readers_notifications();
writer_pending = false;
}

void writer_unlock()
{
notify_all_readers();
guard.unlock();
}

};

------------------------------

Usage example:

rw_mutex_t guard;

void reader_thread()
{
guard.register_reader();
while (!stop)
{
guard.reader_lock();
read_some();
guard.reader_unlock();
}
guard.unregister_reader();

}

void writer_thread()
{
while (!stop)
{
guard.writer_lock();
write_some();
guard.writer_unlock();
sleep_some();
}
}

------------------------------

This mutex is completely new and unpatented and specially put in public domain for free use.

Reader must periodically execute reader_lock()/
reader_unlock() while he is registered. Else it will prevent writer
from acquiring the mutex.

This mutex put additional requirements on reader and writer code. You can see additional thoughts and comments on idea and implementation here:
http://groups.google.ru/group/comp.programming.threads/browse_frm/thread/b7d3b8c08f9ca3c6/#

Comments and thoughts are appreciated.

Dmitriy V'jukov

0 Kudos
0 Replies
Reply