[312] in Pthreads mailing list archive

home help back first fref pref prev next nref lref last post

Semaphores

daemon@ATHENA.MIT.EDU (Alex Tang)
Sun May 5 20:02:50 1996

To: pthreads@MIT.EDU
Date: Sun, 5 May 1996 17:12:01 -0400 (EDT)
Cc: altitude@cic.net
From: Alex Tang <altitude@petrified.cic.net>

Hi folks.

I've just started using pthreads-1_60_beta5 on SunOS414.  I was wondering
if anyone had any hints about implementing semaphores.  I looked at the
man pages at
	http://www.mit.edu/afs/sipb/user/proven/XMOSAIC/pthreads_man.html
but couldn't find them.  I'm assuming that we must provide our own
semaphore support for now.  

I've also got the book "Programming with Threads", by Kleiman, et al.  and
they explain how to implemnt a few semaphore operations on pp. 180-181
(the struct sem_t, sem_wait and sem_post).

I've got this so far:

typedef struct {
    pthread_mutex_t lock;
    pthread_cond_t  nonzero;
    unsigned int    count;
    unsigned int    waiters;
} sem_t;

int sem_wait ( sem_t *sp ) {
    pthread_mutex_lock ( &sp->lock );
    while ( sp->count == 0 ) {
        sp->waiters++;
        pthread_cond_wait ( &sp->nonzero, &sp->lock );
        sp->waiters--;
    }
    sp->count--;
    pthread_mutex_unlock ( &sp->lock );
    return ( 0 );
}

int sem_post ( sem_t *sp ) {
    pthread_mutex_lock ( &sp->lock );
    if ( sp->waiters )
        pthread_cond_signal ( &sp->nonzero );
    sp->count++;
    pthread_mutex_unlock ( &sp->lock );
    return ( 0 );
}

Now i'm trying to do sem_init.  Can anyone tell me if this is ok?  I don't
know how to use the pshared variable (haven't had a need for it yet).  I
also realize that I might need to do more error checking and such...

int sem_init ( sem_t *sp, int pshared, unsigned int value );
/*    	note, we don't have to malloc the sem_t*/
    pthread_mutex_init ( &(sp->lock), NULL );
    pthread_cond_init  ( &(sp->nonzero), NULL );
    sp->count = value;
    sp->waiters = 0;
    return ( 0 );
}

what about sem_destroy?  what should it do?  

int sem_destroy ( sem_t *sp ) {
    pthread_mutex_destroy ( &(sp->lock) );
    pthread_cond_destroy  ( &(sp->nonzero) );
    return ( 0 );
}
 

Thanks a bunch.
...alex...

-- 
    Alex Tang   altitude@cic.net   http://petrified.cic.net/~altitude
	   Viz-It!: Software Developer,   http://vizit.cic.net
   CICNet: Unix Support / Info Services / Programmer, http://www.cic.net

home help back first fref pref prev next nref lref last post