A Synchronized List Class

A Synchronized List Class - int remove SynchList.cc...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
A Synchronized List Class We want to implement a List class where remove() will block if the list is empty. To implement this class, we will use a semaphore “_emptySem” that will be initialized with a counter of 0. Remove() will call sema_wait(&_emptySem) and it will block until insert() calls The counter in semaphore will be equivalent to the number of items in the list.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
A Synchronized List Class SyncList.h #include <pthread.h> struct ListEntry { int _val; ListEntry *_next; }; class SyncList{ ListEntry *_head; pthread_mutex_t _mutex; sema_t _emptySem; public: SyncList(); void insert(int val);
Background image of page 2
Background image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: int remove(); SynchList.cc SyncList:: SyncList(){ _ _head = NULL; pthread_mutex_init( &_mutex, NULL ); sema_init(&_emptySem,0, USYNC_THREAD, NULL); } SyncList ::insert(int val){ ListEntry *e = new ListEntry; e->_val = val; pthread_mutex_lock(&_mutex); a)e->_next = _head; b)_head = e; pthread_mutex_unlock(&_mutex); sema_post(&_emptySem); } A Synchronized List int SyncList ::remove(){ ListEntry *tmp; // Wait until list is not empty sema_wait(&_emptySem); pthread_mutex_lock(&_mutex); c)tmp = _head; d)head=tmp->_next; pthread_mutex_unlock(&mutex); int val=tmp->_val; delete tmp; return val; }...
View Full Document

This note was uploaded on 01/30/2012 for the course CS 354 taught by Professor Staff during the Fall '08 term at Purdue.

Page1 / 3

A Synchronized List Class - int remove SynchList.cc...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online